Forms are everywhere—from login pages to contact forms, they let users interact with your website. But how do you handle form data securely in PHP? That’s exactly what we’ll cover in this step-by-step guide!
By the end, you’ll know how to handle form submissions, prevent security risks, and even build a mini contact form project! 🎯
🎯 How Forms Work in PHP
When a user submits a form, the data is sent to a PHP script for processing. This can be done via:
- GET Method (
$_GET
) – Sends data in the URL. - POST Method (
$_POST
) – Sends data securely in the request body.
1️⃣ Creating a Simple PHP Form
Example: Basic HTML Form
<form action="process.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
✅ What Happens Here?
- The form sends data to
process.php
. - The method is
POST
, so data won’t be visible in the URL.
2️⃣ Handling Form Data in PHP
Let’s create process.php
to capture the form data.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Thank you, $name! We have received your email: $email.";
}
?>
🔍 Breaking It Down
$_POST['name']
captures the form input.htmlspecialchars()
prevents XSS attacks (cross-site scripting).$_SERVER["REQUEST_METHOD"]
ensures the form was submitted usingPOST
.
3️⃣ GET vs. POST: When to Use What?
Method | How It Works | When to Use |
---|---|---|
GET |
Data appears in the URL (example.com?name=Zero+Dev ) |
For search queries, filtering, and pagination |
POST |
Data is hidden (sent in request body) | For logins, signups, and private data |
4️⃣ Validating & Sanitizing User Input
Never trust user input as-is! Validate and sanitize it before using it.
Example: Name Validation
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']); // Remove spaces
if (empty($name)) {
echo "Name is required.";
} elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
echo "Only letters and spaces allowed.";
} else {
echo "Valid name: $name";
}
}
?>
✅ Why?
trim()
removes extra spaces.empty()
checks if the field is blank.preg_match()
ensures only letters and spaces are allowed.
5️⃣ Preventing SQL Injection
If your form inserts data into a database, sanitize input with prepared statements.
Example: Secure Database Insertion
<?php
$conn = new mysqli("localhost", "root", "", "zeroexp_dev");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['name'], $_POST['email']);
$stmt->execute();
echo "Data saved!";
}
?>
🔥 Why? Prepared statements prevent SQL injection attacks!
6️⃣ Handling Checkbox & Radio Buttons
Example: Capturing Checkbox Values
<form method="post">
Select skills:<br>
<input type="checkbox" name="skills[]" value="PHP"> PHP
<input type="checkbox" name="skills[]" value="JavaScript"> JavaScript
<input type="checkbox" name="skills[]" value="CSS"> CSS
<input type="submit" value="Submit">
</form>
Processing the Checkbox Input
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['skills'])) {
echo "Skills: " . implode(", ", $_POST['skills']);
} else {
echo "No skills selected.";
}
}
?>
🔥 Why? implode(", ", $_POST['skills'])
joins selected checkboxes into a readable string.
7️⃣ Handling File Uploads
Example: Uploading an Image
<form method="post" enctype="multipart/form-data">
Select file: <input type="file" name="file"><br>
<input type="submit" value="Upload">
</form>
Processing the File
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
$target = "uploads/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed.";
}
}
?>
✅ What Happens?
- The form allows file selection.
move_uploaded_file()
safely saves the uploaded file.
🎯 Mini Project: Simple Contact Form with Validation
Let’s build a real-world contact form that validates input and prevents spam.
contact.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
if (empty($name) || empty($email) || empty($message)) {
echo "All fields are required!";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format!";
} else {
echo "Thank you, $name! Your message has been sent.";
}
}
?>
<form method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" value="Send">
</form>
🔥 What’s Happening?
- Validates required fields (
empty()
). - Checks email format (
filter_var()
). - Displays success message after validation.
🚀 Final Thoughts
Handling forms correctly is essential for every PHP developer. Now you know how to:
✅ Capture GET & POST data
✅ Validate & sanitize user input
✅ Prevent SQL injection
✅ Handle checkboxes, radio buttons, and file uploads
👉 Next: Validating and Sanitizing User Inputs in PHP
Happy coding! 🎉🚀
This is kinda basic for form handling. Will add a more in-depth post about form handling in future.