PHP form handling involves collecting, validating, and processing data submitted through HTML forms. PHP uses the $_GET and $_POST superglobals to retrieve form data based on the HTTP request method.
- Collecting Data: Retrieves submitted values from form fields.
- Validating Data: Checks whether inputs meet expected requirements.
- Processing Data: Uses the submitted data for tasks such as saving records or sending emails.
- Displaying Responses: Shows confirmation messages or redirects users after submission.
Form Attributes to Submit Data
HTML form attributes control where and how form data is submitted.
| Attribute | Description |
|---|---|
| action | Specifies the URL or PHP script that processes the form. |
| method | Specifies the HTTP method, usually GET or POST. |
| name | Identifies a form field so its submitted value can be accessed in PHP. |
| target | Specifies where to display the response, such as the current tab or a new tab. |
| enctype | Specifies how form data is encoded. Use multipart/form-data for file uploads. |
Example:
<form method="post" action="process_form.php">
<input type="text" name="username" required>
<input type="submit" value="Submit">
</form>
Here, the form sends the username to process_form.php using the POST method. PHP can access the submitted value using $_POST['username'].
Different Input Elements to Collect Data
HTML provides several form elements for collecting different types of user input.
| Element | Purpose | Example |
|---|---|---|
| Text field | Collects single-line text. | <input type="text" name="fullname"> |
| Password field | Hides entered characters visually. | <input type="password" name="password"> |
| Checkbox | Allows users to select one or more options. | <input type="checkbox" name="subscribe" value="yes"> |
| Radio button | Allows users to select one option from a group. | <input type="radio" name="gender" value="female"> |
| Email field | Collects an email address and provides browser-level format checking. | <input type="email" name="email"> |
| Textarea | Collects multiline text. | <textarea name="message"></textarea> |
| Submit button | Submits the form. | <input type="submit" value="Submit"> |
Creates and Processes an HTML Form
The following example creates a form and processes its submitted data on the same page.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Form Handling</title>
</head>
<body>
<form method="post" action="">
<label>
Full Name:
<input type="text" name="fullname" required>
</label>
<br><br>
<label>
Email:
<input type="email" name="user_email" required>
</label>
<br><br>
<label>
Age:
<input type="number" name="user_age" min="1" required>
</label>
<br><br>
<label>
Feedback:
<textarea name="user_feedback" rows="4" required></textarea>
</label>
<br><br>
Gender:
<label>
<input type="radio" name="user_gender" value="female" required>
Female
</label>
<label>
<input type="radio" name="user_gender" value="male">
Male
</label>
<br><br>
<input type="submit" value="Submit">
</form>
<?php
if (($_SERVER["REQUEST_METHOD"] ?? "") === "POST") {
$fullname = trim($_POST['fullname'] ?? '');
$email = trim($_POST['user_email'] ?? '');
$age = $_POST['user_age'] ?? '';
$feedback = trim($_POST['user_feedback'] ?? '');
$gender = $_POST['user_gender'] ?? '';
if (
$fullname !== '' &&
filter_var($email, FILTER_VALIDATE_EMAIL) &&
filter_var($age, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1]
]) !== false &&
$feedback !== '' &&
in_array($gender, ['female', 'male'], true)
) {
echo "<h2>Details Submitted</h2>";
echo "Full Name: " . htmlspecialchars($fullname, ENT_QUOTES, 'UTF-8') . "<br>";
echo "Email: " . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . "<br>";
echo "Age: " . htmlspecialchars((string) $age, ENT_QUOTES, 'UTF-8') . "<br>";
echo "Feedback: " . htmlspecialchars($feedback, ENT_QUOTES, 'UTF-8') . "<br>";
echo "Gender: " . htmlspecialchars($gender, ENT_QUOTES, 'UTF-8');
} else {
echo "Please provide valid form data.";
}
}
?>
</body>
</html>
- Form Submission: The HTML form sends user data to the same page using the POST method.
- Request Checking: $_SERVER['REQUEST_METHOD'] checks whether the current request uses the POST method.
- Data Retrieval: $_POST retrieves the submitted form values, while the null coalescing operator (??) provides default values if keys are missing.
- Validation: filter_var() validates the email address and age, while additional checks ensure that the required fields are not empty and the gender value is valid.
- Output Escaping: htmlspecialchars() escapes user-provided values before displaying them in HTML, helping prevent cross-site scripting (XSS).
Output:
Before submission, the page displays fields for the user's name, email, age, feedback, and gender.
After submitting valid data, PHP displays the submitted details.
Note: htmlspecialchars() helps prevent cross-site scripting (XSS) when displaying data in HTML, but it does not validate input. For applications that store submitted data in a database, use prepared statements to help prevent SQL injection.