Skip to content

Handling HTTP requests in PHP

New Course Coming Soon:

Get Really Good at Git

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

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my PHP Handbook

Here is how can I help you: