Handling HTTP requests in PHP

Let’s see how to handle HTTP requests in PHP.

PHP offers file-based routing by default. You create an index.php file and that responds on the / path.

We saw that when we made the Hello World example in the beginning.

Similarly, you can create a test.php file and automatically that will be the file that Apache serves on the /test route.

$_GET, $_POST and $_REQUEST

Files respond to all HTTP requests, including GET, POST and other verbs.

For any request you can access all the query string data using the $_GET object which is called superglobal and is automatically available in all our PHP files.

This is of course most useful in GET requests, but also other requests can send data as query string.

For POST, PUT and DELETE requests you’re more likely to need the data posted as urlencoded data or using the FormData object, which PHP makes available to you using $_POST.

There is also $_REQUEST which contains all of $_GET and $_POST combined in a single variable.

$_SERVER

We also have the superglobal variable $_SERVER, which you use to get a lot of useful information.

You saw how to use phpinfo() before. Let’s use it again to see the things that $_SERVER offers us.

In your index.php file in the root of MAMP run:

<?php
phpinfo();
?>

then generate the page at localhost:8888 and search $_SERVER, you will see all the configuration stored and the values assigned:

Important ones you might use are

  • $_SERVER['HTTP_HOST']
  • $_SERVER['HTTP_USER_AGENT']
  • $_SERVER['SERVER_NAME']
  • $_SERVER['SERVER_ADDR']
  • $_SERVER['SERVER_PORT']
  • $_SERVER['DOCUMENT_ROOT']
  • $_SERVER['REQUEST_URI']
  • $_SERVER['SCRIPT_NAME']
  • $_SERVER['REMOTE_ADDR']

Download my free PHP Handbook!