PHP Security Practices
Input Validation
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = test_input($_POST["name"]);
?>
Prepared Statements
<?php
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
?>
Password Hashing
<?php
$password = "userpassword";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Verify password
if (password_verify($password, $hashed_password)) {
echo "Password is valid!";
}
?>
CSRF Protection
<?php
// Generate token
$_SESSION['token'] = bin2hex(random_bytes(32));
// In form
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>">
// Verify token
if (!hash_equals($_SESSION['token'], $_POST['token'])) {
die("Invalid CSRF token");
}
?>
Back to Tutorials