Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
HTML Form
2.1.
Example
3.
Form Handling with PHP
3.1.
GET vs. POST
3.2.
When to use GET in PHP?
3.3.
When to use POST in PHP?
3.4.
Which one to use GET or POST
3.5.
Simple HTML Form with PHP form handler
4.
Why use PHP for Form handling
5.
Form Validation
5.1.
PHP Form Validation
6.
PHP Form Security
7.
Frequently Asked Questions
7.1.
What is Cross-site scripting?
7.2.
Can PHP handle forms?
7.3.
Why is form important in PHP?
8.
Conclusion
Last Updated: May 7, 2024
Easy

Form Handling in PHP

Introduction

Forms are like digital questionnaires on websites, helping collect information from users. And PHP, a popular web programming language, is great for making forms work smoothly.

In this blog, we'll take a simple approach to understand how to handle forms in PHP. We'll learn how to get data from users, check if it's correct, and do something with it.

Form Handling in PHP

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..

Example

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.

Which one to use GET or POST

In general, POST is preferred for sending form data. But GET can also be used depending upon the use case.

When using GET, the variables are passed to the PHP script via URL parameters, i.e.,in the URL, all variable names and values are presented. The character count is also limited to around 2000.

GET can be used to send non-sensitive information.

In the case of POST, the form data is embedded within the HTTP request body, i.e., the information is hidden from others.

Additionally, while uploading files to the server, POST enables sophisticated features such as support for multi-part binary input, and there is no character limit.

We will be using the POST method in the following examples.

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.

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;
}
?>

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

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

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.

In general, POST is preferred for sending form data. But GET can also be used depending upon the use case.

GET can be used to send non-sensitive information.

For more PHP blogs kindly visit the following links:

  1. PHP Intro
  2. PHP Syntax and coding styles

Happy learning!!

Live masterclass