Table of contents
1.
Introduction
2.
What is HTML Form?
3.
How to Create a Simple HTML Form?
4.
Form Handling with PHP
4.1.
GET vs. POST
4.2.
When to use GET in PHP?
4.3.
When to use POST in PHP?
4.4.
Simple HTML Form with PHP form handler
5.
Why use PHP for Form handling
6.
Displaying Submitted Data
7.
Form Validation
7.1.
PHP Form Validation
8.
Common Validation Techniques
8.1.
1. Required Field Validation
8.2.
2. Email Validation
8.3.
3. Numeric Validation
8.4.
4. Length Validation
8.5.
5. Regular Expression Validation
8.6.
6. Password Matching
9.
PHP Form Security
10.
Maintaining and Updating Forms
11.
Frequently Asked Questions
11.1.
What is Cross-site scripting?
11.2.
Can PHP handle forms?
11.3.
Why is form important in PHP?
12.
Conclusion
Last Updated: Mar 5, 2025
Easy

PHP Form Handling

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP Form Handling is a crucial aspect of web development that allows websites to collect, process, and manage user input efficiently. Whether it's user registration, login forms, or feedback submissions, PHP provides powerful methods to handle form data securely. Understanding how to receive, validate, and sanitize form input is essential for building dynamic and interactive web applications. In this blog, we'll explore the fundamentals of PHP Form Handling.

Form Handling in PHP

What is HTML Form?

On a web page, a webform, web form, or HTML form permits a user to submit information that is then transferred to a server to be processed. Because web users fill out forms with checkboxes, radio buttons, and text fields, they might mimic paper or database forms. Forms can be used to enter shipping address or credit card information when ordering a product or to receive search engine results..

How to Create a Simple HTML Form?

HTML forms are used to collect user input, such as text, emails, or passwords. Creating a basic form is the first step in form handling.

Below is an example of normal HTML form with two input boxes and a submit button:

<!DOCTYPE HTML> 
<html> 
  <body> 
    <form> 
      Username: <input type="text" name="name"><br> 
      Password: <input type="text" name="password"><br> 
      <input type="submit"> 
    </form> 
  </body> 
</html>

Form Handling with PHP

When using PHP with an HTML form, we specify the URL of the PHP script in the action attribute of the form tag. The data passed by the form is then accessed by the target PHP code using PHP's $_POST or $_GET variables, depending on the value of the form's action attribute ("get" or "post").

GET vs. POST

An Array is created via both GET and POST (for example, array(key1 => value1, key2 => value2, key3 => value3,...)).

The keys are the form's control names, and the values are the user's input data, therefore this array comprises key/value pairs.

Both GET and POST are referred to as $_GET and $_POST, respectively.

These are superglobals, which implies they can be accessed from any function, class, or file, regardless of scope.

When to use GET in PHP?

You should use GET in PHP when you want to pass small amounts of data to the server through the URL. GET appends data to the URL, which makes it visible to users. It's commonly used for fetching data and navigating between pages. However, it's not suitable for sensitive information or large data sets.

When to use POST in PHP?

POST in PHP is used when you need to send large amounts of data or sensitive information to the server. Unlike GET, POST sends data in the background, making it more secure as it's not visible in the URL. It's commonly used for submitting forms, uploading files, and processing user inputs that require confidentiality or involve large data sets.

Simple HTML Form with PHP form handler

The form data is passed to a PHP file named " form handler.php " for processing when the user fills out the form below and clicks the submit button. The HTTP POST method is used to send the form data.

<html> 
  <body> 
    <form action=" form_handler.php" method="post"> 
       Username: <input type="text" name="name"><br> 
       Password: <input type="text" name="password"><br> 
       <input type="submit"> 
    </form> 
  </body> 
</html>

 

PHP Form handler script “form_handler.php”:

<html> 
  <body> 
    Welcome <?php echo $_POST["name"]; ?><br> 
    Your password is: <?php echo $_POST["email"]; ?> 
  </body> 
</html>

 

The above script will simply display the submitted data.

e.g., When submitting the form, the output will be

Welcome Priyanka 

Your Password  is 123***abc

Why use PHP for Form handling

Although client-side scripting can be used to reproduce the previous example, server-side code can perform a wide range of functions to develop dynamic web pages.

Client-side languages are limited when used with forms; client-side code cannot do everything — from authenticating a login to retrieving and saving data in a database, spell checking, and sending an email — for technical or security reasons.

Despite these restrictions, they can frequently be used to pre-validate form data and prepare it for sending to server-side software.

Displaying Submitted Data

Once the form is submitted, PHP can process and display the user input using the $_POST or $_GET superglobal arrays, depending on the form method. This helps in showing the submitted data back to the user or processing it further.

HTML Form (index.html):

<form action="display.php" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <button type="submit">Submit</button>
</form>

 

PHP Code (display.php):

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);

    echo "<h3>Submitted Data:</h3>";
    echo "Name: " . $name . "<br>";
    echo "Email: " . $email . "<br>";
}
?>

Form Validation

It is a "procedure where a web form examines if the information provided by a user is correct."

Validation ensures that the provided text is in the correct format (e.g., user@example.com for email). It meets a valid entry requirement (e.g., the email address isn't already registered, and the password meets the criteria).

It is also mandatory to protect the server from malicious code from hackers and spammers.

PHP Form Validation

Let’s take our previous example and expand upon it.

<!DOCTYPE HTML> <html> <body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"><br><br> 
E-mail: <input type="text" name="email"><br><br> 
Website: <input type="text" name="website"><br><br> 
Comment: <textarea name="comment" rows="5" cols="40"></textarea><br><br>
Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit"> </form>
 </body>
 </html>

 

The first step is to use PHP's htmlspecialchars() function to send all variables through.

If a user uses the htmlspecialchars() function to submit the following in a text field:

<script>location.href('http://www.hacked.com')</script>

 

- it will not be executed since it would be preserved as HTML escaped code, which would be as follows:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

 

The script can now be safely displayed on a web page or in an email.

When the user accepts the form, we'll do two more things:

  1. Trim additional characters from user input data (extra space, tab, newline) with the PHP trim() method.
  2. Using the PHP stripslashes() method, remove backslashes () from user input data.

Next, we have to write a function that will do all of the necessary checks.

The function test will be given a name ().

With the test() function, we can now verify each $_POST variable, and the script looks like this:

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test($_POST["name"]);
  $email = test($_POST["email"]);
  $website = test($_POST["website"]);
  $comment = test($_POST["comment"]);
  $gender = test($_POST["gender"]);
}

 
function test($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

Common Validation Techniques

Validation plays a vital role in ensuring that form data is accurate, secure, and meets the required format before processing. Below are some commonly used validation techniques in PHP:

1. Required Field Validation

Checks if the input field is empty or not. It ensures that the user doesn't leave mandatory fields blank.
Example:

if (empty($_POST['name'])) {
    echo "Name is required.";
}

2. Email Validation

Validates whether the provided email address follows the correct format using PHP's built-in filter.
Example:

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format.";
}

3. Numeric Validation

Checks if the input contains only numeric values, commonly used for fields like age or phone numbers.
Example:

if (!is_numeric($_POST['age'])) {
    echo "Age must be a number.";
}

4. Length Validation

Verifies if the input meets the required minimum or maximum length.
Example:

if (strlen($_POST['password']) < 6) {
    echo "Password must be at least 6 characters long.";
}

5. Regular Expression Validation

Uses regular expressions to validate custom input patterns like phone numbers, names, or passwords.
Example:

if (!preg_match("/^[a-zA-Z ]*$/", $_POST['name'])) {
    echo "Only letters and white spaces are allowed.";
}

6. Password Matching

Compares two input fields to ensure both passwords match (e.g., password and confirm password).
Example:

if ($_POST['password'] != $_POST['confirm_password']) {
    echo "Passwords do not match.";
}

PHP Form Security

For PHP Form validation, we will be using the following HTML code

<form method="post"action="<?phpechohtmlspecialchars($_SERVER["PHP_SELF"]);?>">

 

The superglobal variable $_SERVER["PHP SELF"] returns the filename of the currently running script.

As a result, instead of moving to a separate page, the $_SERVER["PHP SELF"] transmits the submitted form data to the page itself. The user will receive error notifications on the same page as the form in this manner.

However, using the $_SERVER["PHP SELF"] variable by itself poses a security concern, as it can be exploited by hackers!

A user can insert a slash (/) and then certain Cross-Site Scripting (XSS) commands if PHP SELF is utilized in a website.

e.g., Suppose we have the following form in a page named "demo_form.php":

<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">

If a user types "http://www.example.com/test form.php" into the address bar, the following code will be converted to:

<form method="post" action="demo_form.php">

Consider what happens if a user types the following URL into the address bar

http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

In this situation, the code above will be interpreted as:

<form method="post" action="demo_form.php/"><script>alert('hacked')</script>

A script tag and an alert command are added with this code. The JavaScript code will be performed when the page loads (the user will see an alert box). This is merely a simple and harmless example of how the PHP SELF variable can be abused.

Remember,  that we can use any JavaScript code inside the script> tag! The user can be redirected to a file on another server by a hacker. That file could contain malicious code that, for example, changes global variables or sends the form to a different location to save the user's information.

Must Read PHP Projects With Source Code

Maintaining and Updating Forms

Maintaining and updating forms is essential to ensure that your web application remains secure, functional, and user-friendly over time. Regular updates help improve the form's performance, security, and compatibility with modern technologies.

Here are key practices for maintaining and updating forms:

1. Regular Security Updates

Keep your validation rules updated to prevent vulnerabilities like SQL injection and Cross-Site Scripting (XSS). Use functions like:

htmlspecialchars() 
strip_tags() 
mysqli_real_escape_string()

 

2. Improving User Experience

Add modern features like real-time validation or autocomplete to enhance user experience.
Example:

<input type="email" name="email" placeholder="Enter your email" autocomplete="on">

 

3. Error Handling Enhancements

Display more user-friendly error messages and provide hints on how to fix the issue.
Example:

if (empty($_POST['email'])) {
    echo "Please enter your email address.";
}

 

4. Accessibility Improvements

Ensure your forms are accessible to people with disabilities by using ARIA attributes and labels.
Example:

<label for="email">Email:</label>
<input type="email" id="email" name="email" aria-required="true">

 

5. Cross-Browser Compatibility

Test forms on different browsers like Chrome, Firefox, Safari, and Edge to ensure consistent performance.

 

6. Data Validation Updates

Modify validation rules to meet changing business requirements or new legal regulations like GDPR.

Frequently Asked Questions

What is Cross-site scripting?

Cross-site scripting (XSS) is a vulnerability generally found in web applications. XSS enables an attacker to embed code onto a legitimate website that executes when the victim loads the site.

Can PHP handle forms?

We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST. The form request may be get or post.

Why is form important in PHP?

Forms are the basic interface between user and server. Form handling is the very basic and important feature of PHP. Using forms we can accept data from users and then we can handle the data using PHP. Data can be saved in any database server like MySql.

Conclusion

PHP Form Handling plays a crucial role in creating dynamic and interactive web applications by allowing users to submit and process data efficiently. By implementing proper form validation, security measures, and user-friendly features, you can ensure the accuracy, security, and reliability of the collected information. Regular maintenance, updates, and best practices further enhance the functionality and performance of your forms.

For more PHP blogs kindly visit the following links:

  1. PHP Intro
  2. PHP Syntax and coding styles
  3. PHP Projects With Source Code
Live masterclass