$_GET is one of the superglobals in PHP. It is an associative array of variables passed to the current script via the query string appended to the URL of HTTP request. Note that the array is populated by all requests with a query string in addition to GET requests.

$HTTP_GET_VARS contains the same initial information, but that has now been deprecated.

By default, the client browser sends a request for the URL on the server by using the HTTP GET method. A query string attached to the URL may contain key value pairs concatenated by the “&” symbol. The $_GET associative array stores these key value pairs.

Save the following script in the document folder of Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder.

<?php
   echo "<h3>First Name: " . $_REQUEST['first_name'] . "<br />" . 
   "Last Name: " . $_REQUEST['last_name'] . "</h3>";
?>

Start the XAMPP server, and enter “http://localhost/hello.php?first_name=Mukesh&last_name=Sinha” as the URL in a browser window. You should get the following output −

PHP $ GET 1

The $_GET array is also populated when a HTML form data is submitted to a URL with GET action.

Under the document root, save the following script as “hello.html” −

<html><body><form action="hello.php" method="get"><p>First Name: <input type="text" name="first_name"/></p><p>Last Name: <input type="text" name="last_name" /></p><input type="submit" value="Submit" /></form></body></html>

In your browser, enter the URL “http://localhost/hello.html” −

PHP $ GET 2

You should get a similar output in the browser window −

PHP $ GET 3

In the following example, htmlspecialchars() is used to convert characters in HTML entities −

CharacterReplacement
& (ampersand)&amp;
” (double quote)&quot;
‘ (single quote)&#039; or &apos;
< (less than)&lt;
> (greater than)&gt;

Assuming that the URL in the browser is “http://localhost/hello.php?name=Suraj&age=20” −

<?php
   echo  "Name: " . htmlspecialchars($_GET["name"]) . "";
   echo  "Age: " . htmlspecialchars($_GET["age"]) . "<br/>";
?>

It will produce the following output −

Name: Suraj
Age: 20

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *