Site icon Netopsiyon Online

Web Form Example with PHP

Web forms are essential in web applications, and creating secure and user-friendly forms with PHP is crucial. In this article, we will cover form validation and secure data processing using PHP.

1. A Simple HTML Form

Let’s create a form that collects the user’s name, email, and message:

session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
<form action="process.php" method="post">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" required>
    
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required>
    
    <label for="message">Message:</label>
    <textarea name="message" id="message" required></textarea>
    
    <button type="submit">Send</button>
</form>

2. Processing Form Data with PHP

The following PHP script securely processes form data:

session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token!");
    }
    
    $name = htmlspecialchars(trim($_POST['name']));
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(trim($_POST['message']));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email address!";
    } else {
        echo "Thank you, your message has been received.";
        // You can save the data to a database or send an email here.
    }
}

3. Security Measures

  1. CSRF Protection: Add a CSRF token to forms to prevent fake requests.
  2. XSS Protection: Use htmlspecialchars() to sanitize user input.
  3. SQL Injection Prevention: Use prepared statements with PDO for data processing.
Exit mobile version