PHP Form Security

In this tutorial, we’ll show you how to secure your PHP forms. Form security is essential to protect user data from malicious attacks such as SQL injection, cross-site scripting (XSS), and more. Let’s dive into how you can secure your forms and ensure user data is protected.

🔹 Why is Form Security Important?

When processing user input, it’s essential to protect against attacks such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). Without proper security measures, attackers can manipulate your forms to steal sensitive information, inject malicious scripts, or even alter your database. Let’s see how to avoid these issues!


📝 Example 1: SQL Injection Protection

SQL injection is a technique where an attacker injects malicious SQL code into your queries. To protect against this, always use prepared statements and parameterized queries.

<?php
// Create a connection to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];

    // Use prepared statements to prevent SQL injection
    $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->bind_param("ss", $name, $email);  // 'ss' means both are strings
    $stmt->execute();
    
    echo "User added successfully!";
}
?>

Try It Now

In this example, we use prepared statements to securely insert data into the database. This prevents SQL injection attacks, as the user input is treated as data, not executable code.


📝 Example 2: XSS Protection (Cross-Site Scripting)

XSS attacks occur when an attacker injects malicious scripts into your web page. To protect against XSS, we sanitize and escape user input using the htmlspecialchars() function.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize user input to prevent XSS attacks
    $username = htmlspecialchars($_POST['username']);
    $comment = htmlspecialchars($_POST['comment']);
    
    echo "Welcome, $username! Your comment: $comment";
}
?>

Try It Now

In this example, we use htmlspecialchars() to escape special characters like <, >, and ", ensuring that any potentially harmful input is displayed safely, preventing XSS attacks.


🔹 Example 3: CSRF Protection (Cross-Site Request Forgery)

CSRF attacks trick users into performing actions they didn’t intend to. To prevent CSRF, you can use a unique token for each form and verify that the token is valid before processing the form data.

<?php
session_start();

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    // Form processing logic
    $name = htmlspecialchars($_POST['name']);
    echo "Form submitted by $name!";
} else {
    echo "Invalid CSRF token!";
}
?>

Try It Now

In this example, we generate a unique CSRF token for each form and verify it when the form is submitted. This ensures that the form submission is legitimate and not a forged request from another site.


🔹 Example 4: Password Hashing and Salting

When storing passwords, never store them as plain text! Use password_hash() and password_verify() to securely hash and verify passwords.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $password = $_POST['password'];

    // Hash the password with a strong algorithm (e.g., bcrypt)
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Verify the password (in a real scenario, compare it with the stored hash)
    if (password_verify($password, $hashed_password)) {
        echo "Password is correct!";
    } else {
        echo "Password is incorrect!";
    }
}
?>

Try It Now

Here, we use password_hash() to hash the password using bcrypt, a strong and secure hashing algorithm. When the user logs in, we can use password_verify() to verify that the entered password matches the stored hash.


🎯 Best Practices for Form Security:

  • Always use prepared statements to prevent SQL injection attacks.
  • Sanitize and escape user input using htmlspecialchars() to prevent XSS attacks.
  • Implement CSRF protection by adding a unique token to each form and verifying it on submission.
  • Never store plain text passwords—always use password_hash() and password_verify() for password security.
  • Validate and filter input to ensure it’s safe and matches expected formats (e.g., email, URLs).

📝 Practice Time!

Try adding more security measures, such as CAPTCHA to prevent bots or rate limiting to prevent brute force attacks. Always keep your forms and application secure!