PHP Security Best Practices

1. Prevent SQL Injection

Always use prepared statements or parameterized queries to prevent SQL injection attacks.

// Bad (vulnerable to SQL injection)
$query = "SELECT * FROM users WHERE username = '$username'";

// Good (using prepared statement)
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);

2. Protect Against Cross-Site Scripting (XSS)

Always sanitize and validate user input, and use output encoding when displaying data.

// Sanitize input
$clean_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_SPECIAL_CHARS);

// Output encoding
echo htmlspecialchars($user_data, ENT_QUOTES, 'UTF-8');

3. Implement Proper Authentication and Session Management

Use secure password hashing and implement proper session management to protect user accounts.

// Password hashing
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Verifying password
if (password_verify($input_password, $hashed_password)) {
    // Password is correct
}

// Secure session management
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
session_start();

4. Use HTTPS

Always use HTTPS to encrypt data in transit. You can enforce HTTPS in your PHP application:

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

5. Protect Against Cross-Site Request Forgery (CSRF)

Implement CSRF tokens to protect against cross-site request forgery attacks.

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// In your form
echo '';

// Validate CSRF token
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die('CSRF token validation failed');
}