To prevent SQL injection in PHP:
- Use Prepared Statements: Use parameterized queries or prepared statements with PDO (PHP Data Objects) or MySQLi to bind user inputs securely.
Example (PDO):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
- Input Validation: Validate and sanitize user inputs to ensure they match the expected format or values.
- Escaping: If you can’t use prepared statements, escape user inputs with
mysqli_real_escape_string()
for MySQL orpg_escape_string()
for PostgreSQL.
Example (MySQLi):
$username = mysqli_real_escape_string($conn, $username);
- Avoid Dynamic Queries: Avoid constructing SQL queries using string concatenation with user inputs.
- Limit Database Permissions: Grant minimal database privileges to the application, limiting its ability to modify the database structure.
By following these practices, you can significantly reduce the risk of SQL injection in PHP.