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.
Superglobal $_GET in PHP
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
- This URL includes query parameters, name and age, with values "JohnDoe" and "30," respectively.
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>
- 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']).
- If both parameters exist, we retrieve their values with $_GET['name'] and $_GET['age'].
- We then display a personalized message with the name and age extracted from the URL.
- 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).
×