Open In App

Common Mistakes to Avoid in PHP

PHP is a widely used server-side scripting language for web development. However, developers often overlook best practices, leading to vulnerabilities and inefficiencies. This article delves into common PHP mistakes and offers comprehensive solutions.

Not Using Prepared Statements

// Mistaken code
$query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "'";

Syntax:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute([$username]);

Ignoring Error Handling

// Mistaken code
$result = $pdo->query("SELECT * FROM users");

Syntax:



try {
// Code that may throw an exception
} catch (Exception $e) {
// Handle the exception
}

Poor Password Security

// Mistaken code
$password = $_POST['password'];

Syntax:

$options = ['cost' => 12];
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, $options);

Lack of Input Validation

// Mistaken code
$email = $_POST['email'];

Syntax:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Invalid email format
}

Mixing PHP and HTML

// Mistaken code
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>

Syntax:

// In a separate file, e.g., welcome.php
<h1>Welcome,
<?php echo $username; ?>!</h1>

Example

Example 1: Prepared Statements

$stmt = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->execute([$username, $password]);

Example 2: Error Handling

try {
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
} catch (PDOException $e) {
die("Error executing query: " . $e->getMessage());
}

Example 3: Password Hashing

$options = ['cost' => 12];
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, $options);

Example 4: Input Validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format");
}

Example 5: Separating PHP and HTML

// In a separate file, e.g., welcome.php
<h1>Welcome, <?php echo $username; ?>!</h1>
Article Tags :