PHP $_POST method

Explain the $_POST method in PHP with an example?

You can use $_POST global variable to retrieve data from an HTML form which have it's method attributes value as 'post'. The $_POST variable contains value of all the form elements in an array format name of the form element become key and its value will be value of the form element which is sent by the HTTP POST method. Whatever information user fill in form and sent to server it remain invisible to all the users, therefore post method is convenient for critical information or kind of applications where data required security. And you can send more data through 'post' method as compare to 'get' method. The example is mentioned below: Code


<html>
  <body>
    <form action="myPHPScript.php" method="post" name="myform">
      Enter your first name: 
      <input type="text" name="txtFirstName" id="txtFirstName" />
Enter your last name: <input type="text" name="txtLastName" id="txtLastName" />
Enter your address: <input type="text" name="txtAddress" id="txtAddress" />
<input type="submit" name="save" id="save" value="Save"> </form> </body> </html>
In above mentioned example HTML page have three input fields and a submit button. When a user fills values in this form and click on the 'Save' button, then the form data will be sent to the "myPHPScript.php" php file, it is because we set action attribute as myPHPScript.php file, if you want to receive data on any other file then set your file name as action attribute's value. And method attribute set as 'post'. Now in below mentioned example we shown the code of myPHPScript.php file and how can we access forms value through $_POST. The "myPHPScript.php" file looks like this:
Code

<html>
  <body>
    Welcome Mr. <?php echo $_POST["txtFirstName"]; ?>.
Your address is <?php echo $_POST["txtAddress"]; ?>. </body> </html>
The output of the above mentioned example:

Welcome Mark.
Your address is US.

FAQ 1. Does the POST method display submitted data in the URL? No. The POST method sends form data in the HTTP request body rather than displaying it in the URL. 2. Can we send multiple input values using the POST method? Yes. We can submit multiple form fields, such as name, email, age, and address, using a single POST request. 3. What happens when a user submits an empty form? PHP may receive empty strings for submitted fields. We can use empty() to check whether a field contains a value.