Process POST Data in PHP

Introduction: This tutorial is on how to handle POST data in PHP. POST? POST Data in PHP is data that has been sent behind the scenes from another page, or external source, which can be accessed by the page being sent the information. POST is one of the two methods available to use through HTML Forms. I will be talking about the other method 'GET', in another tutorial. HTML Form: Here is a basic POST HTML form...
  1. <head></head>
  2. <body>
  3. <form action='page.php' method='POST'>
  4. <input type='text' name='user' />
  5. <input type='submit' />
  6. </form>
  7. </body>
  8. </html>
This would create a basic HTML form consisting of a submit button, and a textbox with the name of 'user' which would be where the user would enter their username for something such as a register or login form for an accounts website. The submit input is a simple Submit button to submit the form information. As you can see from the 'METHOD' of the form, it is a 'POST' method form. This means any data will be sent behind the scenes to the destination location, which in this case is 'page.php' which can be found through the 'action' attribute of the HTML form. Processing: To process the data, we first create our PHP section...
  1. <?php
  2. //PHP Here
  3. ?>
Now, within those PHP tags, we can first check if the post variable with the key name of 'user' is set. If you recall, this is the text input of our basic HTML form above...
  1. if (isSet($_POST['user'])) {
  2.  
  3. }else{
  4.  
  5. }
Next we can create a local variable named 'user' to hold our value the user put in to our 'user' input textbox of our HTML form...
  1. $user = $_POST['user'];
Finally we could output this new variable on to our page. If it isn't set, we could output 'Not set', like so by using the inbuilt PHP function 'echo' (or 'print')...
  1. if (isSet($_POST['user'])) {
  2. $user = $_POST['user'];
  3. echo $user;
  4. }else
  5. echo 'Not set.';
We could then do more advanced things such as inserting the data in to our database, other files, or processing the data even further. Finished!

Add new comment