CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

PHP - $_GET

PHP - $_GET

$_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.

How Does $_GET Work?

When someone visits a URL like this βˆ’

PHP CODE
http://localhost/hello.php?name=Amit&age=22

PHP can access the values using $_GET.

PHP CODE
<?php
   echo "Hello, " . $_GET['name'] . "!";
   echo " You are " . $_GET['age'] . " years old.";
?>

Output

Here is the outcome of the following code βˆ’

PHP CODE
Hello, Amit! You are 22 years old.

Example

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 CODE
<?php
   echo "<h3>First Name: " . $_REQUEST['first_name'] . "<br />" . 
   "Last Name: " . $_REQUEST['last_name'] . "</h3>";
?&gt;

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 followingoutputβˆ’

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” βˆ’

Preview

In your browser, enter the URL”http://localhost/hello.htmlβ€βˆ’

You should get a similaroutputin the browser window βˆ’

HTML Special Characters

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

CharacterReplacement& (ampersand)&” (double quote)”’ (single quote)’ or β€˜< (less than)<> (greater than)>

Assuming that the URL in the browser is β€œhttp://localhost/hello.php?name=Suraj&age=20” βˆ’

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

It will produce the followingoutputβˆ’

PHP CODE
Name: Suraj
Age: 20