← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 11 of 24

PHP Security Best Practices

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
<?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";
?>

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
<?php
$comment = "<script>alert('xss')</script>";
echo htmlspecialchars($comment);
?>

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
<?php
$hash = password_hash("secret123", PASSWORD_DEFAULT);
var_dump(password_verify("secret123", $hash));
?>

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
<?php
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
echo "Token embedded in form, verified with hash_equals() on submit";
?>

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
<?php
$email = "[email protected]";
echo filter_var($email, FILTER_VALIDATE_EMAIL) ? "Valid" : "Invalid";
?>

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.