PHP Form Handling β Step-by-Step Guide
What is PHP Form Handling?
Form handling in PHP refers to the process of collecting user input from an HTML form, processing it, and displaying or storing it.
π Common Uses:
- User registration & login forms
- Contact forms
- Feedback and surveys
- Search forms
HTML Form Basics
Before handling form data, we need to create an HTML form:
<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" required>
<label for="email">Email:</label>
<input type="email" name="email" required>
<input type="submit" value="Submit">
</form>
πΉ method="POST"
β Sends form data securely.
πΉ action="process.php"
β Sends data to process.php
for handling.
πΉ required
attribute β Ensures fields are not empty.
Handling Form Data with PHP ($_POST & $_GET)
Using $_POST
Method (Recommended for Security)
$_POST
is used for sending data securely (hidden in HTTP requests).
π Example: process.php
(Handling Form Data)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email);
}
?>
β
Why use htmlspecialchars()
?
- Prevents Cross-Site Scripting (XSS) attacks.
- Converts special characters like
<script>
into safe text.
Using $_GET Method (Data Visible in URL)
$_GET
is used when you want data to be visible in the URL (e.g., search queries).
π Example: Sending data via URL
<form action="process.php" method="GET">
<input type="text" name="query">
<input type="submit" value="Search">
</form>
π Example: Receiving $_GET
data
<?php
if (isset($_GET["query"])) {
echo "Search term: " . htmlspecialchars($_GET["query"]);
}
?>
β οΈ Warning: Avoid using $_GET
for sensitive data like passwords.
Validating User Input (Best Practices)
πΉ 1. Check if fields are empty
if (empty($_POST["name"])) {
echo "Name is required.";
}
πΉ 2. Validate email format
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
}
πΉ 3. Use trim()
to remove spaces
$name = trim($_POST["name"]);
πΉ 4. Allow only specific characters (e.g., names should not contain numbers)
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
echo "Only letters and spaces allowed.";
}
Preventing Security Threats
β
1. Prevent XSS (Cross-Site Scripting)
Use htmlspecialchars()
to escape HTML tags.
$name = htmlspecialchars($_POST["name"]);
β
2. Prevent SQL Injection (if storing in a database)
Use prepared statements with PDO or MySQLi.
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);
β 3. Validate CSRF Tokens (Preventing Cross-Site Request Forgery)
session_start();
if ($_POST["csrf_token"] !== $_SESSION["csrf_token"]) {
die("Invalid CSRF token");
}
Displaying Form Data (Using PHP & HTML Together)
<?php
$name = isset($_POST["name"]) ? htmlspecialchars($_POST["name"]) : "";
$email = isset($_POST["email"]) ? htmlspecialchars($_POST["email"]) : "";
?>
<form method="POST">
<label>Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>">
<label>Email:</label>
<input type="email" name="email" value="<?php echo $email; ?>">
<input type="submit" value="Submit">
</form>
π Why is this useful?
- If there’s an error, the user doesnβt have to re-enter data.
Redirecting After Form Submission
Avoid form resubmission issues by using header()
:
header("Location: success.php");
exit();
Storing Form Data in a Database
Step 1: Connect to a Database
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
Step 2: Insert Data Securely
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$_POST["name"], $_POST["email"]]);
β Always use prepared statements to prevent SQL injection.
Sending Form Data via Email
$to = "admin@example.com";
$subject = "New Form Submission";
$message = "Name: " . $_POST["name"] . "\nEmail: " . $_POST["email"];
$headers = "From: noreply@example.com";
mail($to, $subject, $message, $headers);
Summary: PHP Form Handling Best Practices
πΉ Use $_POST
for sensitive data (e.g., passwords).
πΉ Use $_GET
for search queries and navigation.
πΉ Validate and sanitize input to prevent security risks.
πΉ Use prepared statements for database interactions.
πΉ Prevent XSS and CSRF attacks with htmlspecialchars()
and tokens.
πΉ Redirect users after form submission to prevent duplicate entries.