How to Use the $_GET Superglobal in PHP

This article explains how the $_GET superglobal works in PHP to collect and process data sent through the URL query string. You will learn how PHP populates this predefined array, how to access its values in your scripts, and the essential security practices required to handle this data safely.

What is the $_GET Superglobal?

In PHP, $_GET is a superglobal variable, meaning it is an associative array that is automatically available in all scopes throughout your script. It is used to collect data sent via an HTTP GET request. This data is passed to the server by appending parameters to the end of the URL, known as a query string.

A typical URL with a query string looks like this: http://example.com/index.php?name=John&age=30

In this URL, the query string starts after the question mark (?). It contains two key-value pairs separated by an ampersand (&): * name with a value of John * age with a value of 30

How PHP Processes $_GET Data

When PHP receives a request with a query string, it automatically parses the parameters and places them into the $_GET associative array. You can access these values using their corresponding keys.

Here is a basic code example demonstrating how to retrieve and display these values:

<?php
// Check if the expected parameters exist in the URL
if (isset($_GET['name']) && isset($_GET['age'])) {
    // Retrieve the values from the $_GET array
    $name = $_GET['name'];
    $age = $_GET['age'];

    echo "Hello, " . $name . ". You are " . $age . " years old.";
} else {
    echo "Please provide a name and age in the URL.";
}
?>

If you visit index.php?name=John&age=30, the output will be: Hello, John. You are 30 years old.

Crucial Security Practices

Data sent via the URL can be easily modified by anyone. Because of this, you must never trust user input. When using $_GET in your applications, always apply these two security steps:

1. Sanitization and Escaping

To prevent Cross-Site Scripting (XSS) attacks, never output raw $_GET data directly to the browser. Always escape the output using htmlspecialchars():

// Safe output to prevent XSS
echo "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

2. Validation and Filtering

Ensure the incoming data is of the expected type. For example, if you expect an integer for age, you can cast it or use PHP’s filter functions:

// Validate that age is an integer
$age = filter_input(INPUT_GET, 'age', FILTER_VALIDATE_INT);

if ($age === false) {
    echo "Invalid age provided.";
}

Key Characteristics of $_GET