PHP Security Best Practices
In this page:
Preventing SQL Injection
SQL injection happens when raw user input gets concatenated directly into a query string; prepared statements with bound parameters (via PDO) separate the query structure from the data, making injection structurally impossible.
Example: Preventing SQL Injection
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER, name TEXT)");
$stmt = $pdo->prepare("INSERT INTO users (id, name) VALUES (?, ?)");
$stmt->execute([1, "Alice"]);
echo "Injection-proof: data is bound, not concatenated";
?>
Login to try C/C++/Java/PHP code in the editor
Preventing Cross-Site Scripting (XSS)
Cross-site scripting lets an attacker inject malicious script into a page other users view; htmlspecialchars() converts characters like < and > into safe HTML entities before you echo any user-supplied text.
Example: Preventing Cross-Site Scripting (XSS)
<?php
$comment = "<script>alert('xss')</script>";
echo htmlspecialchars($comment);
?>
Login to try C/C++/Java/PHP code in the editor
Safe Password Hashing
password_hash() applies a strong, salted one-way hash to a password before storage, and password_verify() checks a login attempt against it -- storing raw passwords should never happen under any circumstances.
Example: Safe Password Hashing
<?php
$hash = password_hash("secret123", PASSWORD_DEFAULT);
var_dump(password_verify("secret123", $hash));
?>
Login to try C/C++/Java/PHP code in the editor
Preventing CSRF Attacks
CSRF tricks a logged-in user's browser into submitting a request they never intended; embedding a random, per-session token in every form and verifying it on submit blocks forged requests from other sites.
Example: Preventing CSRF Attacks
<?php
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
echo "Token embedded in form, verified with hash_equals() on submit";
?>
Login to try C/C++/Java/PHP code in the editor
Validating and Sanitizing Inputs
filter_var() with constants like FILTER_SANITIZE_EMAIL or FILTER_VALIDATE_URL gives you a consistent, tested way to clean and validate common input types instead of writing fragile custom regex for each one.
Example: Validating and Sanitizing Inputs
<?php
$email = "[email protected]";
echo filter_var($email, FILTER_VALIDATE_EMAIL) ? "Valid" : "Invalid";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser