PHP $_GET Superglobal
PHP $_GET
The $_GET superglobal contains an array of variables received via the HTTP GET method.
PHP superglobals are built-in variables that are always accessible in all scopes!
There are two main ways to send variables via the HTTP GET method:
- via query strings in the URL
- via HTML forms with method="get"
$_GET via URL Query Strings
A query string is data added to the end of a URL. In the <a> element below, everything after the
? sign is the query string:
HTML link with URL query parameters:
<html>
<body>
<a href="demo_phpfile.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
The query string above contains two key/value pairs:
- subject=PHP
- web=W3schools.com
In the PHP file we can use the $_GET
superglobal to collect the value of the query string.
Example
The PHP file demo_phpfile.php:
<html>
<body>
<?php
$subject = htmlspecialchars($_GET['subject']);
$web = htmlspecialchars($_GET['web']);
echo "Study $subject at $web.";
?>
</body>
</html>
Try it Yourself »
Note: Always validate and sanitize all
data collected from superglobals like $_GET
before using it, to prevent security vulnerabilities like XSS attacks. The
htmlspecialcars() function
used above is one way to do it. More robust filtering can be done by using the
PHP filter functions.
$_GET in HTML Forms
A HTML form submits information via the HTTP GET method if
the form's method attribute is set to "get".
To demonstrate this, we start by creating a simple HTML form:
HTML file:
<html>
<body>
<form action="welcome_get.php" method="GET">
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button, the form data is sent to the PHP file specified in the
action attribute of the
<form> tag.
The form fields are sent to the PHP file, with the user input, as query strings:
welcome_get.php?name=John&email=john@example.com
In the PHP file we can use the $_GET variable
to collect the value of the input fields.
Example
PHP code inside the welcome_get.php page:
<html>
<body>
Welcome <?php echo htmlspecialchars($_GET["name"]); ?><br>
Your email address is: <?php echo htmlspecialchars($_GET["email"]); ?>
</body>
</html>
Run Example »
Think SECURITY when processing forms and user input!
The examples above does not contain much form validation, it just shows how you can send and retrieve form data. Proper validation of form data is important to protect you from hackers and spammers!
Learn more about processing PHP forms with security in mind in the Form Validation chapter.