agyanadda@gmail.com

PHP Security Best Practices

OOP and Advanced PHP 1 min read Updated Dec 1, 2026 Topic 36 of 36

Most hacked PHP sites fall to the same few mistakes. Follow this checklist.

1. SQL injection

Use prepared statements (PDO placeholders) for every query with user data.

2. XSS (Cross-Site Scripting)

Escape every output: htmlspecialchars($value, ENT_QUOTES, 'UTF-8'). Blade's {{ }} does this automatically.

3. CSRF (Cross-Site Request Forgery)

Add a secret token to every POST form and check it on submit:

$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) { exit('Invalid request'); }

Laravel's @csrf does this for you.

4. Passwords

  • Store with password_hash($password, PASSWORD_DEFAULT)
  • Check with password_verify()
  • Never use md5() or sha1() for passwords

5. Sessions

session_regenerate_id(true) after login, HTTPS everywhere, httponly and secure cookies.

6. File uploads

Check size and real MIME type, rename files, never allow .php.

7. Configuration

  • display_errors = Off on live servers
  • Keep passwords in .env or config files outside the public folder
  • Keep PHP and packages updated (composer update, composer audit)
  • Give the database user only the permissions it needs

8. Validate everything

Check type, length, format and allowed values for all input — $_GET, $_POST, $_COOKIE, headers and uploaded files.

Example

Example — Secure form with CSRF token and password hashing PHP
<?php
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));

function e(string $v): string
{
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) {
        http_response_code(419);
        exit('Invalid or expired form. Please reload the page.');
    }

    $name = trim($_POST['name'] ?? '');
    $password = $_POST['password'] ?? '';

    if (mb_strlen($password) < 8) {
        $message = 'Password must be at least 8 characters.';
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        // Save $name and $hash with a prepared statement here
        $message = 'Account created for ' . e($name) . '.<br>Stored hash starts with: ' . e(substr($hash, 0, 20)) . '...';
        $message .= '<br>Password check: ' . (password_verify($password, $hash) ? 'match ✓' : 'no match');
    }
}
?>
<form method="post">
  <input type="hidden" name="csrf" value="<?= e($_SESSION['csrf']) ?>">
  <input name="name" placeholder="Name" required>
  <input name="password" type="password" placeholder="Password (8+ characters)" required>
  <button>Create account</button>
</form>
<p><?= $message ?></p>

The form includes a hidden CSRF token that must match the session. The password is stored only as a secure hash (it starts with $2y$), and password_verify() checks it at login.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function should you use to store passwords?

Exercise 2 True / False

A CSRF token protects forms from being submitted by other websites.

Exercise 3 Fill in the Blank

Escaping output with htmlspecialchars() prevents ___ attacks.

Frequently Asked Questions

Laravel handles CSRF, escaping, password hashing and prepared queries by default, but you can still create holes (e.g. {!! !!} with user data, raw queries, weak upload checks). The same rules apply.