How to Retrieve and Process HTML Form Data Using PHP
HTML forms are one of the most common ways to collect user input on a webpage. However, to process that data, you need a backend and that's where PHP comes in. In this tutorial, you’ll learn how to retrieve and process HTML form data using PHP.
By the end, you’ll know how to send data from a form to a PHP script and use it, whether you're saving it to a database, sending an email, or displaying it on the screen.
Let’s get started.
Step 1: Set Up Your Project Files
Create two files for this tutorial
- index.html – Your frontend form where users will enter their data.
- process.php – A PHP script that handles and processes the submitted form data.
Tip: Place both files in the same folder for easier access and testing.
Step 2: Create the HTML Form (index.html)
Paste the following code into your index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
- The <form> tag’s action attribute points to process.php, which will handle the data.
- method="POST" ensures data is sent securely in the request body, not visible in the URL.
- The <input> fields collect user data.
Step 3: Process the Form Data in PHP (process.php)
Next, write the backend PHP code in your process.php file
<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
// Sanitize output to prevent XSS
echo "Welcome, " . htmlspecialchars($name) . "!<br>";
echo "Your email address is: " . htmlspecialchars($email);
} else {
echo "No data submitted.";
}
?>
Explanation:
- isset() checks whether the form fields were submitted.
- $_POST retrieves the data sent from the form.
- htmlspecialchars() protects against cross-site scripting (XSS) by escaping special characters.
- You can expand this script to insert data into a database or send it via email.
Important Points to Remember
- Case Sensitivity: Form field names and PHP variable names are case-sensitive.
- File Location: Keep both index.html and process.php in the same directory.
- Security: Always validate and sanitize user input before using it in any application logic or database.
You've now learned how to create a basic HTML form, link it to a PHP script, and retrieve the data submitted by users. This is a foundational skill in web development and is the first step toward building interactive and data-driven web applications.
If you found this tutorial helpful, be sure to visit Coder Sikarwar for more web development tips and tutorials.
Thanks for reading!