Bootstrap FreeKB - PHP - $_GET request
PHP - $_GET request

Updated:   |  PHP articles

In PHP, there are two similar built in variables, $_GET and $_POST. Take the following URL as an example.

http://www.freekb.net?foo=bar

 

In this example, "foo" is the key and "bar" is the value. Here is how you can GET the content of the foo key, a value of bar.

<?php
  echo $_GET['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($_GET['foo'])) and !empty($_GET['foo'])) {
    echo $_GET['foo'];
  }
  else {
    echo "The foo key either does not exist or contains an empty value";
  }
?>

 

The URL can contain multiple key value pairs.

http://www.freekb.net?foo=Hello&bar=World

 

And then you would do something like this.

<?php
  echo $_GET['foo'];
  echo $_GET['bar'];
?>

 

When debugging some issue, print_r can be used to print the content of the $_GET 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 ($_GET);
?>

 

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

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

 

Which should return the following.

foo = Hello
bar = World

 

It's super easy to include the key value pairs when using an a href to create a link to another web page.

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

 

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

<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

 




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 720d41 in the box below so that we can be sure you are a human.