start learning
Image 1
5011223354562

Superglobal $_GET in PHP

In PHP, $_GET is a superglobal variable used to collect data sent to the server through the URL query parameters. When a user interacts with a web page and includes data in the URL (e.g., via links or form submissions using the GET method), PHP can capture and process that data using the $_GET superglobal. $_GET is an associative array containing key-value pairs, where the keys are parameter names, and the values are the data associated with those parameters.


Example with Clarification :

Let's create an example to illustrate how to use the $_GET superglobal to retrieve data sent via URL query parameters.

URL with Query Parameters :

Assume that a user accesses a URL like this :

http://example.com/index.php?name=JohnDoe&age=30

Retrieving Data with $_GET:

Now, let's create a PHP script to capture and display the data from the URL using the $_GET superglobal.

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>URL Parameter Example</h1>
    
    <?php
    if (isset($_GET['name']) && isset($_GET['age'])) {
        $name = $_GET['name'];
        $age = $_GET['age'];
        echo "<p>Hello, $name! Your age is $age years.</p>";
    } else {
        echo "<p>No data provided via URL parameters.</p>";
    }
    ?>
</body>
</html>
  1. In this PHP script, we check if the name and age query parameters exist in the URL using isset($_GET['name']) and isset($_GET['age']).
  2. If both parameters exist, we retrieve their values with $_GET['name'] and $_GET['age'].
  3. We then display a personalized message with the name and age extracted from the URL.
  4. If the parameters are not provided in the URL, we display a message indicating that no data was provided via URL parameters.

This example demonstrates how to use the $_GET superglobal to retrieve and process data sent via URL query parameters. It's commonly used for various purposes, such as passing search queries, filters, or page identifiers in web applications. Remember to validate and sanitize data received through $_GET to prevent security vulnerabilities, such as SQL injection or cross-site scripting (XSS).


×