In this tutorial, you’ll learn how to use the $_GET
superglobal in PHP to retrieve data from URL query strings, enabling you to handle parameters passed in the URL.
PHP Superglobal $_GET
1. What is the $_GET Superglobal?
The $_GET
superglobal is an associative array in PHP that allows you to access variables sent via URL query strings using the HTTP GET method. This is commonly used for passing data between pages.
2. Sending Data Using URL Query Strings
To send data using $_GET
, you can include parameters in the URL. For example:
http://www.example.com/page.php?name=John&age=25
In this example, name
and age
are the parameters being passed to page.php
.
3. Accessing Data with $_GET
To retrieve the values of the query parameters, you can use the $_GET
superglobal as follows:
<?php
$name = $_GET['name'];
$age = $_GET['age'];
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
?>
This code retrieves the name
and age
parameters and displays them.
4. Checking if Parameters Exist
Before accessing $_GET
variables, it’s good practice to check if they are set to avoid undefined index notices. You can do this using the isset()
function:
<?php
if (isset($_GET['name']) && isset($_GET['age'])) {
$name = $_GET['name'];
$age = $_GET['age'];
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
} else {
echo "Parameters not set.";
}
?>
5. URL Encoding
When sending data through URLs, special characters should be URL-encoded to ensure proper transmission. Use urlencode()
to encode query parameters:
<?php
$name = urlencode("John Doe");
$url = "http://www.example.com/page.php?name=" . $name;
echo "URL: " . $url;
?>
This will convert spaces and special characters into a format suitable for URLs.
6. Security Considerations
When using $_GET
, always validate and sanitize input data to prevent security vulnerabilities such as XSS (Cross-Site Scripting) and SQL injection. Use functions like htmlspecialchars()
and prepared statements for database interactions.
7. Conclusion
The $_GET
superglobal is a powerful tool for retrieving data from URLs in PHP. By understanding how to use it effectively, you can build dynamic web applications that respond to user input through URL parameters.