PHP Form Handling

PHP form handling refers to how PHP processes data submitted through an HTML form. Here's a basic overview and example to help you understand how it works.


1. HTML Form

Create an HTML form where users can input data:

<form action="process.php" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email"><br><br> <input type="submit" value="Submit"> </form>
  • action="process.php" — this tells the browser to send the form data to process.php.

  • method="post" — data will be sent via HTTP POST (you can also use get).


2. PHP Script to Handle the Form (process.php)

Create a file named process.php:

<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Collect form data and sanitize it $name = htmlspecialchars($_POST['name']); $email = htmlspecialchars($_POST['email']); echo "Name: " . $name . "<br>"; echo "Email: " . $email; } else { echo "Form not submitted correctly."; } ?>
  • $_POST['name'] and $_POST['email'] access the submitted form data.

  • htmlspecialchars() prevents XSS (cross-site scripting) by escaping HTML characters.


3. Security Tips

  • Always validate and sanitize user input.

  • Use filter_var() for better validation (e.g., filter_var($email, FILTER_VALIDATE_EMAIL)).

  • Use HTTPS to protect data in transit.