Bootstrap FreeKB - PHP - $_POST request
PHP - $_POST request

Updated:   |  PHP articles

In PHP, there are two similar built in variables, $_GET and $_POST. Before working with POST, it's much easier to first understand GET. 

Let's say an a href is used to create a link to another web page. Notice in this example that foo=bar was included in the URL. In this example, "foo" is the key and "bar" is the value.

<a href="http://www.freekb.net?foo=bar"></a>

 

Or using the Location header to redirect to another web page.

header("location: http://www.freekb.net?foo=bar");

 

Or let's say www.freekb.net/page1.php contains the following. Notice in this example that the method is GET.

<form method="get" action="page2.php">
  <input type="text" name="foo">
  <button>Submit</button>
</form>

 

At page1.php, something like this should be displayed.

 

After clicking submit, you would be directed to page2.php with the following URL.

http://www.freekb.net/page2.php?foo=Hello%20World

 

POST is different. With POST, the key and value pairs are not included in the URL. Let's say www.freekb.net/page1.php contains the following. Notice in this example that the method is POST.

<form method="post" action="page2.php">
  <input type="text" name="foo">
  <button>Submit</button>
</form>

 

Just like a GET request, at page1.php, something like this should be displayed.

 

After clicking submit, you would be directed to page2.php with the following URL. Notice the foo key and value of "Hello World" are NOT included in the URL.

http://www.freekb.net/page2.php

 

However, you can still get the content of the foo key via a $_POST request.

<?php
  echo $_POST['foo'];
?>

 

Often, it's a good idea to use isset and not empty to ensure the "foo" key exists and contains a value.

<?php
  if(isset($_POST['foo'])) and !empty($_POST['foo'])) {
    echo $_POST['foo'];
  }
  else {
    echo "The foo key either does not exist or contains an empty value";
  }
?>

 

When debugging some issue, print_r can be used to print the content of the $_POST variable.

<?php
  print_r ($_GET);
?>

 

Which should return something like this.

Array ( [foo] => Hello [bar] => World )

 

Or var_dump can be used as well.

<?php
  var_dump ($_POST);
?>

 

Or you can loop through the array and print the keys and values.

<?php
  foreach ($_POST as $key => $value) {
    echo $key . ' = ' . $value . '<br \>';
  }
?>

 

Which should return the following.

foo = Hello
bar = World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b6b005 in the box below so that we can be sure you are a human.