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()orsha1()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 = Offon live servers- Keep passwords in
.envor 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
<?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.