← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 10 of 10

PHP Common Mistakes & Best Practices

Loose vs Strict Equality

== silently converts operand types before comparing, which produces surprising results like 0 == abc evaluating to true in older PHP versions; === compares both value and type, avoiding that entire class of bug.

Example: Loose vs Strict Equality

php
<?php
var_dump("0" == "abc");
var_dump("0" === "abc");
?>

Uninitialized Array Keys

Reading an array key that was never set triggers a warning (or an error in strict contexts); checking isset() or array_key_exists() first avoids both the warning and any downstream logic relying on an undefined value.

Example: Uninitialized Array Keys

php
<?php
$user = ["name" => "Alice"];
if (isset($user['email'])) {
    echo $user['email'];
} else {
    echo "Email key not set";
}
?>

SQL Injection Vulnerabilities

Directly concatenating user input into a SQL string opens the door to injection attacks that can read or destroy your entire database; prepared statements eliminate the risk by keeping data separate from query structure.

Example: SQL Injection Vulnerabilities

php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER, name TEXT)");
$name = "Robert'); DROP TABLE users;";
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->execute([$name]);
echo "Safe -- prepared statement kept structure and data separate";
?>

Variable Scope Leaks

Overusing global variables makes it hard to know what a function actually depends on or might change, since its behavior isn't fully described by its parameters -- keeping state local and passed explicitly avoids that hidden coupling.

Example: Variable Scope Leaks

php
<?php
$counter = 0;
function increment() {
    global $counter;
    $counter++;
}
increment();
echo $counter;
// Depending on a global hides this function's real dependency
?>

Best Practices Checklist

A solid production checklist -- validate every input, handle errors consistently, and turn off error display -- catches the majority of security and reliability issues before they ever reach real users.

Example: Best Practices Checklist

php
<?php
$email = $_POST['email'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email";
}
ini_set('display_errors', '0');
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.