
PHP is a widely-used scripting language for web development. However, developers often encounter common mistakes that can lead to frustrating bugs or security vulnerabilities.
Here are some of the most frequent PHP errors and how to fix them:
1. Undefined Variable
Error
Error: Trying to use a variable that has not been defined.
PHP
echo $name;
PHP
$name = 'Ali';
echo $name;
isset()
or empty()
:
PHP
if (isset($name)) {
echo $name;
} else {
echo 'Variable is not defined!';
}
2. Headers Already Sent
Error
Error: Using header()
after output has already been sent to the browser.
PHP
echo 'Welcome!';
header('Location: homepage.php');
header()
before any HTML or echo:
PHP
header('Location: homepage.php');
exit;
echo 'Welcome!';
ob_start()
:
PHP
ob_start();
echo 'Welcome!';
header('Location: homepage.php');
ob_end_flush();
3. Vulnerable to SQL Injection
Error: Using user input directly in SQL queries without validation.
PHP
$query = 'SELECT * FROM users WHERE username = '' . $_GET['username'] . ''';
PDO
or sanitize data with mysqli_real_escape_string()
:
PHP
$stmt = $db->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$_GET['username']]);
$result = $stmt->fetch();
Related Articles

Reusable PHP Functions for Various Projects
0 Comments
Comments ()
No comments yet. Be the first to comment!