Basic PHP Errors & Problems
When working with PHP, developers often encounter various errors and issues. These can be broadly categorized into syntax errors, logical errors, and runtime errors. Below are some common PHP errors, their causes, and solutions.
1. Syntax Errors (Parse Errors)
These errors occur due to incorrect PHP syntax. The script fails to execute.
Example:
<?php
echo “Hello World”
?>
Error Message:
Parse error: syntax error, unexpected end of file in script.php on line 3
Solution:
- Ensure all statements end with a semicolon (;).
- Check for missing or extra brackets, quotes, and parentheses.
- Use an IDE with syntax highlighting.
Corrected Code:
<?php
echo “Hello World”;
?>
2. Undefined Variables
Using a variable that hasn’t been defined or initialized will cause a warning.
Example:
<?php
echo $username;
?>
Error Message:
Notice: Undefined variable: username in script.php on line 2
Solution:
- Always initialize variables before using them.
- Use isset() or empty() to check if a variable exists.
Corrected Code:
<?php
$username = “John”;
echo $username;
?>
3. Undefined Array Key
Trying to access an array element that doesn’t exist.
Example:
<?php
$arr = [“name” => “Alice”];
echo $arr[“age”];
?>
Error Message:
Warning: Undefined array key “age” in script.php on line 3
Solution:
Use isset() or the null coalescing operator (??).
Corrected Code:
<?php
echo $arr[“age”] ?? “Age not set”;
?>
4. Wrong Data Type Errors
Passing unexpected data types to a function.
Example:
<?php
function add($a, $b) {
return $a + $b;
}
echo add(“5”, []);
?>
Error Message:
Fatal error: Uncaught TypeError: Unsupported operand types: string + array
Solution:
Use type hinting and validation.
Corrected Code:
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add(5, 3);
?>
5. Header Already Sent Error
Sending headers after outputting content causes this error.
Example:
<?php
echo “Welcome!”;
header(“Location: home.php”);
?>
Error Message:
Warning: Cannot modify header information – headers already sent
Solution:
- Call header() before any output.
- Use ob_start() to buffer output.
Corrected Code:
<?php
ob_start();
header(“Location: home.php”);
ob_end_flush();
?>
6. Fatal Error: Call to Undefined Function
Occurs when calling a function that doesn’t exist.
Example:
<?php
myFunction();
?>
Error Message:
Fatal error: Uncaught Error: Call to undefined function myFunction()
Solution:
- Ensure the function is defined before calling it.
- Check for spelling mistakes.
Corrected Code:
<?php
function myFunction() {
echo “Hello!”;
}
myFunction();
?>
7. Database Connection Errors
Errors occur due to incorrect database credentials or connection failure.
Example:
<?php
$conn = new mysqli(“localhost”, “root”, “”, “non_existent_db”);
?>
Error Message:
Warning: mysqli::__construct(): (HY000/1049): Unknown database ‘non_existent_db’
Solution:
- Verify database name, username, and password.
- Use mysqli_connect_error() to debug.
Corrected Code:
<?php
$conn = new mysqli(“localhost”, “root”, “”, “my_database”);
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
8. File Not Found Errors
Trying to include a non-existent file.
Example:
<?php
include “config.php”;
?>
Error Message:
Warning: include(config.php): Failed to open stream
Solution:
- Use file_exists() before including a file.
- Use require_once() instead of include() if the file is critical.
Corrected Code:
<?php
if (file_exists(“config.php”)) {
include “config.php”;
} else {
echo “File not found!”;
}
?>
9. Infinite Loop Causing Timeout
An incorrectly written loop can cause infinite execution.
Example:
<?php
while (true) {
echo “Running…”;
}
?>
Error Message:
Fatal error: Maximum execution time exceeded
Solution:
- Ensure loop termination conditions are correct.
- Set a maximum execution time using set_time_limit().
Corrected Code:
<?php
$counter = 0;
while ($counter < 5) {
echo “Running…”;
$counter++;
}
?>
10. Security Issues (SQL Injection)
Using user input directly in SQL queries can lead to SQL injection.
Example:
<?php
$username = $_GET[‘username’];
$query = “SELECT * FROM users WHERE username = ‘$username'”;
$result = mysqli_query($conn, $query);
?>
Solution:
- Use prepared statements to prevent SQL injection.
Corrected Code:
<?php
$stmt = $conn->prepare(“SELECT * FROM users WHERE username = ?”);
$stmt->bind_param(“s”, $username);
$stmt->execute();
$result = $stmt->get_result();
?>
Conclusion
Understanding these common PHP errors and applying best practices can significantly improve the reliability and security of your applications. Always enable error reporting in development environments with:
error_reporting(E_ALL);
ini_set(‘display_errors’, 1);
For production, disable error display and log errors instead:
ini_set(‘display_errors’, 0);
ini_set(‘log_errors’, 1);
ini_set(‘error_log’, ‘errors.log’);