Post Method in PHP

In this tutorial, we will learn how to send data to a web server using POST method in PHP. The POST method is one of the most commonly used HTTP request methods in web development and API integration. Like the GET method, the POST method is also used to send the data to the server for processing.

However, in the POST method, the data is sent to the web server as a package in HTTP Headers rather than simply appended to the end of the URL. Therefore, data sent through the POST method will not be visible in the URL.

Unlike the GET method, which includes data in the URL, the POST method stores the data in the request body of the HTTP request. This makes it more secure and suitable for sending large amounts of data.

Since POST method does not append data at the end of URL as GET method does, it cannot be bookmarked or cached by browser which can be good or bad, depending on your goals.

Key Points for POST Method in PHP


There are some key points about POST method in PHP that you should keep in mind while using it. They are:

  • The POST method is primarily used for sending data from a client (like an HTML form) to a server.
  • It can send the data of any length because of no physical limit like in the GET method.
  • The POST method can send both ASCII and binary data.
  • Since POST uses the HTTP request body to send data, the security of data depends on the HTTP protocol used. For example, by using HTTPs, you can get the security of data.
  • Data sent using POST method is not visible in the URL, making it more secure for sensitive information like passwords.
  • Since POST data is not included in the URL, so it cannot be bookmarked or shared via URL.
  • POST requests are not cached by browsers, unlike GET requests which may be cached.
  • Because of no size limitations in POST method, it is suitable for sending large amounts of data, such as text content or file data.
  • It is often used with AJAX to send data to the server without refreshing the page.
  • POST requests are more secure than GET but should still be validated and sanitized to prevent security issues like XSS or SQL injection.

$_POST Super Global Variable


PHP provides a predefined superglobal array variable called $_POST to receive the form data after submitting an HTML form with the method “POST”. Here, the term global means they are always accessible from any function, class or file regardless of their scope.

The data is accessed through array keys of the global variables $_POST. The general syntax to access the form data through array keys is as:

$variable_name = $_POST['input_name'];

In this syntax,

  • $_POST is a superglobal associative array in PHP that stores the data sent from an HTML form using the POST method.
  • ‘input_name’ is the name attribute of the form field in the HTML form. It is the key used to retrieve the corresponding value from the $_POST array.
  • $variable_name is the PHP variable where you’re storing the input value.

Example:

<input type="text" name="username">
$username = $_POST['username']

Creating A Simple HTML Form using POST Method


Let’s create a simple HTML form using the POST method, which includes input fields, such as name, email, and a submit button. Open your text editor and type the following HTML code.

HTML Code: index.html

<!DOCTYPE html>
<html>
<head>
   <title>Simple HTML Form with POST</title>
</head>
<body>
   <h2>Contact Form</h2>
   <form method="POST" action="process.php">
   <label for="name">Name:</label><br>
      <input type="text" name="name" id="name" required><br><br>

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

      <input type="submit" value="Submit">
   </form>
</body>
</html>

In the above HTML form, the <form> tag contains an attribute named action, which is used to nominate the PHP script that will process (i.e. handle) the form data. In this case, the PHP script is “process.php”.

Besides of it, the <form> tag also contains an attribute named method, which is used to specify how the data will send to the script, typically via the POST method. So, the <form> tag with both attributes looks like this:

<form method="POST" action="process.php">

Now save it as index.html. Start a new file in your editor and type the following PHP code.

PHP Code: process.php

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

   echo "<h2>Form Submitted Successfully!</h2>";
   echo "Name: " . $name . "<br>";
   echo "Email: " . $email;
}
?>

Explanation:

Save this file as process.php. Let’s break down and understand each part of the above PHP code in detail:

(1) The line if ($_SERVER[“REQUEST_METHOD”] == “POST”) { checks if the form has been submitted using the POST method. In other words, the PHP script will only process the form data when the form is submitted via POST.


(2) Inside the parentheses of If statement, the $_SERVER[“REQUEST_METHOD”] tells you which HTTP method has been used to access the page. It returns the request method used to access the page.

(3) The code inside the if block will only execute if the form has submitted using the POST method. Since the condition is true, the script will proceed to retrieve and display the form data.

(4) The line $name = $_POST[“name”]; retrieves the value entered in the Name input field of the HTML form. The superarray variable $_POST[‘name’] retrieves the value from the HTTP POST request body. For example, if “John” is entered in the name field, $_POST[‘name’] returns “John”, which is stored in the variable $name.

(5) Similarly, the line $email = $_POST[“email”]; retrieves the value entered in the Email input field. The returned value is stored in the variable named $email.

(6) After that, we have used the echo statement to display the submitted data on the web page. The <br> tag adds a line break for formatting.

Now open index.html in your browser and type the following information, such as name and email. After entering information, click on the submit button. You will see the following output on your browser.

Output:
      Form Submitted Successfully!
      Name: John
      Email: john@example.com

URL will be like this: “http://localhost/PHP_Project/FormHandling/index.html”.

How Does HTML Form Work with PHP Using POST Method?


An HTML form in combination with PHP allows you to collect data from users and process it on the server side using the POST method. When a user fills out an HTML form and clicks the Submit button, the browser sends the entered data to the server as part of an HTTP POST request.

When the POST method is invoked by adding a method attribute to the <form> tag in the HTML document, the browser does not include the encoded data in a query string. It bundles up the data and puts it into HTTP request body.

In simple words, with method=”POST”, data is sent in the HTTP request body, not appended to the URL (unlike GET). This makes POST more suitable for handling sensitive or large amounts of data.


The server-side PHP script, such as process.php, receives the submitted form data using the $_POST superglobal variable. PHP processes this data on the server — for example, it may validate input, save it to a database, or generate a dynamic response.

Working with HTML Form in PHP using POST method.

After processing the data, the script process.php sends an HTTP response back to the browser. This response typically contains a result or message that is displayed on the web page, allowing the user to see the result of their submitted data.

The destination file (i.e., process.php) is defined in the action attribute of the <form> tag, and the method of data transmission is specified using the method attribute, which is set to “POST” in this case.

When to Use POST Method in PHP?


You can use the predefined POST method in PHP when you need to send a large amount of data securely from a client (browser) to a server in a PHP application. It is preferred in those situations where data needs to be hidden from the URL, processed securely, or involves the modification of server-side resources such as databases or files.

There are the following use cases for the POST method that you should keep in mind. They are:

  • Use the POST method for form submission such as login form, contact form, etc.
  • POST method is the best suitable for sending confidential or private data, such as passwords, credit card details, or personal information. This is because data is sent within the body of the HTTP request. It’s not visible in the browser URL or history.
  • You can use the POST method to send a large amount of data because of no size limitations.
  • Use the POST method when you want to prevent data from being cached/bookmarked. This is because POST data is not saved in browser history or URL.
  • Since GET does not handle binary data or file, you can use POST to upload files by setting enctype=”multipart/form-data” in the form.
  • You can use POST to change the data on the server. For example, you can insert new user records in a database, update profile information, and submit blog posts or comments.
  • AJAX often uses POST to send data to the server without reloading the page. This improves user experience by allowing dynamic updates and real-time interactions.

When Not to Use POST Method?


You can avoid the POST method for:

  • Simple queries (like search or filtering).
  • Actions that do not modify server-side data.
  • Data that users may want to bookmark or share.

In those cases, use GET method instead of POST method.

Difference between GET and POST Methods in PHP


Following are the main difference between GET and POST methods in PHP that you should note down:

1. Data Length:

  • With the GET method, you cannot send a large amount of data because the request parameters are appended to the URL, which has a length limitation.
  • On the other hand, with the POST method, you can send a large amount of data because the request parameters are included in the HTTP request body, not in the URL.

2. Security:

  • GET request is less secure because the data is exposed in the URL bar, browser history, and server logs. Therefore, it is not suitable for transmitting sensitive information like passwords or other personal data.
  • POST request is more secure than GET because the data is sent in the HTTP request body and is not visible in the URL.

3. Types of Data:

  • In the GET method, only ASCII characters are allowed directly.
  • In the POST method, all types of data are allowed, including ASCII, binary, form fields, file uploads, and JSON.

4. Bookmark:

  • Users can bookmark GET requests because all data is included in the URL.
  • On the other hand, users cannot bookmark POST requests because the data is sent in the HTTP request body, not the URL.

5. Parameters:

  • GET parameters remain in the browser history because they are part of the URL.
  • POST parameters are not saved in the browser history because they are sent in the request body.

6. Efficient:

  • GET is more efficient in terms of speed and resource usage for retrieving data because of caching and simpler requests.
  • POST is less efficient compared to GET for data retrieval, but it’s the correct choice when you want to send or modify data.

7. Use Cases:

  • GET is used for those works that do not modify server data, like search queries, filters, or retrieving information.
  • POST is used for those actions that involve data submission, like login forms, registration, contact forms, or file uploads.