TL;DR
Protect your simple PHP forms from common attacks by validating input, escaping output, using prepared statements (if using a database), and implementing basic security measures like CSRF protection. This guide shows you how.
1. Input Validation
Always check what the user enters before doing anything with it. This prevents malicious code or unexpected data from breaking your script or compromising your system.
- Required Fields: Make sure essential fields aren’t left blank.
- Data Type: Check if numbers are actually numbers, emails look like emails, etc.
- Length Limits: Prevent overly long inputs that could cause problems.
2. Escaping Output
When you display user input on your website, make sure it’s safe. Escaping converts potentially harmful characters into a harmless form.
- HTML Entities: Use
htmlspecialchars()to escape special HTML characters (like <, >, &).
3. Database Security (if applicable)
If your form saves data to a database, never directly insert user input into SQL queries. This is the biggest security risk.
- Prepared Statements: Use prepared statements with placeholders. These separate the query structure from the data.
prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$_POST["name"], $_POST["email"]]);
?>
4. CSRF Protection
Cross-Site Request Forgery (CSRF) attacks trick users into performing actions they didn’t intend to. A token helps prevent this.
- Generate a Token: Create a unique, random token for each form.
- Include the Token in the Form: Add it as a hidden field.
- Verify the Token on Submission: Check if the submitted token matches the one you generated.
<input type="hidden" name="csrf_token" value="">
// Verify token on submission
if ($_POST['csrf_token'] !== $_SESSION['csrf_token'])
{
die("CSRF Token invalid!");
}
?>
5. Other Important Considerations
- Rate Limiting: Limit the number of form submissions from a single IP address to prevent brute-force attacks.
- Password Handling (if applicable): Never store passwords in plain text! Use strong hashing algorithms like bcrypt or Argon2.
- Keep Software Updated: Regularly update PHP and any libraries you use to patch security vulnerabilities.

