Web Analytics

PHP Security Best Practices

Advanced~30 min read

Security is critical for web applications! Learn to protect against XSS, CSRF, SQL injection, and implement proper password hashing!

Output
Click Run to execute your code

Password Hashing

<?php
// Hash password
$hash = password_hash('user_password', PASSWORD_DEFAULT);

// Verify password
if (password_verify('user_password', $hash)) {
    echo "Password correct";
}
?>

Prevent XSS

<?php
$userInput = $_POST['comment'];
$safe = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $safe; // Safe to display
?>

CSRF Protection

<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Validate token
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("CSRF validation failed");
}
?>

Summary

  • password_hash(): Secure password storage
  • htmlspecialchars(): Prevent XSS
  • Prepared statements: Prevent SQL injection
  • CSRF tokens: Prevent cross-site attacks

What's Next?

Next, learn about Composer & Packages - modern dependency management!