
PHP Forms: Handling, Validation, Required Fields, URL and Email
Forms are one of the most important parts of web development. They allow users to send information to a website, such as contact messages, login details, registration data, search keywords, comments, and profile information.
In PHP, forms are commonly handled using the $_GET and $_POST superglobals. After receiving the submitted data, the developer usually validates the input, checks required fields, verifies email and URL formats, and then processes the final result.
This article explains the main PHP form topics shown in the learning path: PHP form handling, PHP form validation, PHP form required fields, PHP form URL and email validation, and a complete PHP form example.
PHP Form Handling
PHP form handling means receiving data submitted from an HTML form and processing it on the server side. A form usually sends data using one of two common HTTP methods: GET or POST.
The GET method sends form data through the URL query string. This method is useful for search forms, filters, and pages where the submitted data can safely appear in the browser URL.
The POST method sends form data inside the request body. This method is preferred for contact forms, login forms, registration forms, and any form that sends private or larger data.
A simple HTML form can look like this:
<form method="post" action="process.php">
<label>Name:</label>
<input type="text" name="name">
<label>Email:</label>
<input type="text" name="email">
<button type="submit">Send</button>
</form>In the PHP file, the submitted values can be accessed using $_POST.
<?php
$name = $_POST["name"] ?? "";
$email = $_POST["email"] ?? "";
echo $name;
echo $email;
?>The null coalescing operator ?? is used to avoid errors when a value does not exist. If the form field is missing, PHP will use an empty string instead.
It is also common to check the request method before processing a form.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = $_POST["name"] ?? "";
$email = $_POST["email"] ?? "";
echo "Form submitted.";
}
?>This prevents the form processing code from running before the user actually submits the form.
PHP Form Validation
Form validation means checking user input before accepting or saving it. Validation is important because users may submit empty, incorrect, incomplete, or unsafe data.
PHP form validation can check many things, such as whether a field is empty, whether an email has a valid format, whether a URL is correct, whether a value is numeric, or whether a text length is within an allowed range.
A basic validation structure usually creates an array of errors, checks each input, and then decides whether the form is valid.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "") {
$errors[] = "Name is required.";
}
if ($email === "") {
$errors[] = "Email is required.";
}
if (count($errors) === 0) {
echo "Form is valid.";
}
}
?>The trim() function removes extra spaces from the beginning and end of a string. This is useful because a field containing only spaces should not be treated as valid input.
Validation should happen on the server side even if the form also uses HTML validation in the browser. Browser validation improves user experience, but it can be bypassed. Server-side validation is necessary for security and data correctness.
Sanitizing PHP Form Input
Before displaying user input back on the page, it should be escaped to reduce the risk of cross-site scripting attacks. In PHP, htmlspecialchars() is commonly used for safe output.
<?php
$name = "<script>alert('test')</script>";
echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
?>This converts special HTML characters into safe text. Instead of running as HTML or JavaScript, the input is displayed as normal text.
A simple helper function can make this easier:
<?php
function cleanInput($value) {
return htmlspecialchars(trim($value), ENT_QUOTES, "UTF-8");
}
?>This function trims the value and prepares it for safe display. However, sanitizing output is not a replacement for validation. Validation checks whether data is acceptable, while escaping protects how data is displayed.
PHP Form Required
Required fields are fields that the user must fill before the form can be accepted. Common required fields include name, email, password, subject, message, and agreement checkboxes.
In HTML, you can mark a field as required using the required attribute.
<input type="text" name="name" required>However, PHP should still check required fields on the server side. A user can disable browser validation or send a request manually without using the form interface.
<?php
$errors = [];
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");
if ($name === "") {
$errors["name"] = "Name is required.";
}
if ($email === "") {
$errors["email"] = "Email is required.";
}
if ($message === "") {
$errors["message"] = "Message is required.";
}
?>Using an associative array for errors makes it easier to display each error near its related field.
<?php if (!empty($errors["name"])): ?>
<p><?php echo $errors["name"]; ?></p>
<?php endif; ?>Required validation improves the quality of submitted data and prevents incomplete records from being saved or sent.
PHP Form URL/E-mail
Many forms need to validate emails and URLs. For example, a contact form may require an email address, while a profile form may allow a personal website, LinkedIn profile, GitHub link, or portfolio URL.
PHP provides the filter_var() function for validating common formats such as email and URL.
Email validation can be done using FILTER_VALIDATE_EMAIL.
<?php
$email = trim($_POST["email"] ?? "");
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address.";
}
?>URL validation can be done using FILTER_VALIDATE_URL.
<?php
$website = trim($_POST["website"] ?? "");
if (!filter_var($website, FILTER_VALIDATE_URL)) {
echo "Invalid website URL.";
}
?>If the URL field is optional, the code should validate it only when the user enters a value.
<?php
$website = trim($_POST["website"] ?? "");
if ($website !== "" && !filter_var($website, FILTER_VALIDATE_URL)) {
echo "Invalid website URL.";
}
?>This way, the user can leave the optional URL empty, but if they provide a value, it must be a valid URL.
For email fields, developers usually make the field required and validate its format. For URL fields, the field may be optional depending on the form purpose.
Displaying Form Errors
A good form should clearly show validation errors to the user. Instead of showing one general message, it is better to display specific messages near the fields that need correction.
For example, if the email is missing, the user should see that the email field is required. If the email format is invalid, the user should see that the email address is not valid.
<?php if (!empty($errors["email"])): ?>
<span class="error"><?php echo $errors["email"]; ?></span>
<?php endif; ?>This improves the user experience and makes the form easier to complete.
It is also useful to keep the previously entered values in the form after a validation error. This prevents users from retyping everything again.
<input type="text" name="name" value="<?php echo $name ?? ''; ?>">When displaying old values, remember to escape them using htmlspecialchars().
<input type="text" name="name" value="<?php echo htmlspecialchars($name ?? '', ENT_QUOTES, 'UTF-8'); ?>">PHP Form Complete
A complete PHP form usually includes the HTML form, server-side validation, required field checks, email validation, optional URL validation, safe output, error messages, and success handling.
The following example demonstrates a complete contact form in one PHP file.
<?php
$name = "";
$email = "";
$website = "";
$message = "";
$errors = [];
$success = false;
function oldValue($value) {
return htmlspecialchars($value, ENT_QUOTES, "UTF-8");
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$website = trim($_POST["website"] ?? "");
$message = trim($_POST["message"] ?? "");
if ($name === "") {
$errors["name"] = "Name is required.";
}
if ($email === "") {
$errors["email"] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Please enter a valid email address.";
}
if ($website !== "" && !filter_var($website, FILTER_VALIDATE_URL)) {
$errors["website"] = "Please enter a valid URL.";
}
if ($message === "") {
$errors["message"] = "Message is required.";
} elseif (strlen($message) < 10) {
$errors["message"] = "Message must be at least 10 characters.";
}
if (count($errors) === 0) {
$success = true;
/*
Here you can:
- Save data to a database
- Send an email
- Store a support ticket
- Redirect the user
*/
}
}
?>
<?php if ($success): ?>
<p>Your message has been sent successfully.</p>
<?php endif; ?>
<form method="post" action="">
<div>
<label>Name</label>
<input type="text" name="name" value="<?php echo oldValue($name); ?>">
<?php if (!empty($errors["name"])): ?>
<small><?php echo $errors["name"]; ?></small>
<?php endif; ?>
</div>
<div>
<label>Email</label>
<input type="text" name="email" value="<?php echo oldValue($email); ?>">
<?php if (!empty($errors["email"])): ?>
<small><?php echo $errors["email"]; ?></small>
<?php endif; ?>
</div>
<div>
<label>Website</label>
<input type="text" name="website" value="<?php echo oldValue($website); ?>">
<?php if (!empty($errors["website"])): ?>
<small><?php echo $errors["website"]; ?></small>
<?php endif; ?>
</div>
<div>
<label>Message</label>
<textarea name="message"><?php echo oldValue($message); ?></textarea>
<?php if (!empty($errors["message"])): ?>
<small><?php echo $errors["message"]; ?></small>
<?php endif; ?>
</div>
<button type="submit">Send Message</button>
</form>This complete example shows the main idea behind PHP form processing. It receives data, validates required fields, checks email and URL formats, displays errors, keeps old values, and shows a success message when the form is valid.
Security Notes for PHP Forms
Forms are connected directly to user input, so they must be handled carefully. Never trust user input without validation and escaping.
Important security practices include:
Validate all required fields on the server side.
Escape output using htmlspecialchars().
Use filter_var() for email and URL validation.
Use prepared statements when saving form data to a database.
Protect sensitive forms with CSRF protection in real applications.
Do not display raw user input without escaping.
Limit field lengths to prevent unexpected large input.
In frameworks such as Laravel, many of these tasks are handled using built-in validation, request classes, CSRF protection, and escaping helpers. However, understanding pure PHP form handling is important because it explains what happens behind the scenes.
How PHP Forms Are Used in Real Projects
PHP forms are used in many types of real web applications. A contact page uses a form to receive messages. A login page uses a form to receive email and password. A registration page uses a form to create a new account. An admin panel uses forms to create, update, and delete content.
Common examples of PHP forms include:
Contact forms.
Login and registration forms.
Search forms.
Profile update forms.
Blog post creation forms.
Product management forms.
File upload forms.
Newsletter subscription forms.
Once you understand form handling and validation, you can build more practical PHP applications that interact with users and store meaningful data.
Conclusion
PHP forms are a core part of web development. They allow users to submit data and allow developers to build interactive features such as contact pages, login systems, registration forms, dashboards, and admin panels.
To work with PHP forms correctly, you need to understand form handling, validation, required fields, email and URL validation, safe output, and complete form workflows.
After mastering these concepts, the next step is to connect forms with databases, use sessions for login systems, handle file uploads, and organize validation logic in a cleaner structure using modern PHP or frameworks such as Laravel.

