PHP - Get URL parameters

Introduction

The following code shows how to inspect the URL that the user used to access our application, and extract some information from there.

Save this content as your index.php:

<?php 
$looking = isset($_GET['title']) || isset($_GET['author']); 
?> 
<!DOCTYPE html> 
<html> 
<body> 
   <p>You lookin'? <?php echo (int) $looking; ?></p> 
   <p>The book you are looking for is</p> 
   <ul> 
        <li><b>Title</b>: <?php echo $_GET['title']; ?></li> 
        <li><b>Author</b>: <?php echo $_GET['author']; ?></li> 
    </ul> 
</body> 
</html> 

Now access the link, http://localhost:8000/?author=Jason&title=my book

For each request, PHP stores all the parameters that come from the query string in an array called $_GET.

Each key of the array is the name of the parameter, and its associated value is the value of the parameter.

So $_GET contains two entries: $_GET['author'] contains Jason and $_GET['title'] has the value my book.

Here, we assign a Boolean value to the variable $looking.

If either $_GET['title'] or $_GET['author'] exists, that variable will be true, otherwise false.

We cast a Boolean to an integer means that the result will be 1 if the Boolean is true or 0 if the Boolean is false.

As $looking is true since $_GET contains valid keys, the page shows a "1".

If we try to access the same page without sending any information, as in http://localhost:8000, the browser will say Are you looking for a book? 0.

Related Topics