The Wayback Machine - https://web.archive.org/web/20240816082620/https://www.geeksforgeeks.org/php-superglobals/
Open In App

PHP | Superglobals

Last Updated : 29 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We already have discussed about variables and global variables in PHP in the post PHP | Variables and Data Types. In this article, we will learn about superglobals in PHP.

These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context. The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc. They are mainly used to store and get information from one page to another etc in an application. 

Below is the list of superglobal variables available in PHP: 

  1. $GLOBALS
  2. $_SERVER
  3. $_REQUEST
  4. $_GET
  5. $_POST
  6. $_SESSION
  7. $_COOKIE
  8. $_FILES
  9. $_ENV

Let us now learn about some of these superglobals in detail:  

  • $GLOBALS : It is a superglobal variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[] where index holds the global variable name, which can be accessed.
    Below program illustrates the use of $GLOBALS in PHP: 

PHP




<?php
$x = 300;
$y = 200;
 
function multiplication(){
    $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
 
multiplication();
echo $z;
?>


Output : 

60000

In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function multiplication() is defined to multiply the values of $x and $y and store in another variable $z defined in the GLOBAL array.

  • $_SERVER : It is a PHP super global variable that stores the information about headers, paths and script locations. Some of these elements are used to get the information from the superglobal variable $_SERVER.
    Below program illustrates the use of $_SERVER in PHP: 

PHP




<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
echo "<br>"
?>


Output : 

In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using ‘PHP_SELF’ element. Then we get server name used currently using ‘SERVER_NAME’ element. And then we get the host name through ‘HTTP_HOST’.

  • $_REQUEST : It is a superglobal variable which is used to collect the data after submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.
    Below is the HTML and PHP code to explain how $_REQUEST works: 

HTML




<!DOCTYPE html>
<html>
<body>
 
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
 NAME: <input type="text" name="fname">
 <button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_REQUEST['fname']);
    if(empty($name)){
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>
</body>
</html>


Output : 

In the above code we have created a form that takes the name as input from the user and prints it’s name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code. The data is retrieved using the $_REQUEST superglobal array variable

  • $_POST : It is a super global variable used to collect data from the HTML form after submitting it. When form uses method post to transfer data, the data is not visible in the query string, because of which security levels are maintained in this method.
    Below is the HTML and PHP code to explain how $_POST works: 

HTML




<!DOCTYPE html>
<html>
<body>
  
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
 <label for="name">Please enter your name: </label>
 <input name="name" type="text"><br>
 <label for="age">Please enter your age: </label>
 <input name="age" type="text"><br>
 <input type="submit" value="Submit">
 <button type="submit">SUBMIT</button>
</form>
<?php
$nm=$_POST['name'];
$age=$_POST['age'];
echo "<strong>".$nm." is $age years old.</strong>";
?>
</body>
</html>


Output : 

In the above code we have created a form that takes name and age of the user and accesses the data using $_POST super global variable when they submit the data. Since each superglobal variable is an array it can store more than one values. Hence we retrieved name and age from the $_POST variable and stored them in $nm and $age variables.

  • $_GET : $_GET is a super global variable used to collect data from the HTML form after submitting it. When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.
    Below is the HTML and PHP code to explain how $_GET works: 

HTML




<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="cyan">   
    <?php
        $name = $_GET['name'];
        $city = $_GET['city'];
        echo "<h1>This is ".$name." of ".$city."</h1><br>";
    ?>
    <img src = "2.jpg" alt = "nanilake" height = "400" width="500" />
</body>
</html>


We are actually seeing half of the logic just now. In the above code we have created a hyperlink image of Nainital Lake which will take us to picture.php page and with it will also take the parameters name=”Nainilake” and city=”Nainital”.
That is when we click on the small image of Nainital Lake we will be taken to the next page picture.php along with the parameters. As the default method is get, these parameters will be passed to the next page using get method and they will be visible in the address bar. When we want to pass values to an address they are attached to the address using a question mark (?).

Here the parameter name=Nainilake is attached to the address. If we want to add more values, we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is added using ampersand after the name parameter. Now after clicking on the image of Nainital Lake we want the picture.php page to be displayed with the value of parameter displayed along with it.
 

 



Previous Article
Next Article

Similar Reads

PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
LAMP installation and important PHP configurations on Ubuntu
PHP is the Web development (Server Side Scripting Language) written and developed for web developers.It was developed by Rasmus Lerdorf in 1994, for maintaining his personal homepage. Later he added the feature to communicate with web forms and to connect with databases, named it as Personal Home Page Tools (PHP), Lerdorf wrote those using C binari
5 min read
PHP | imagecreatetruecolor() Function
The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size. Syntax: resource imagecreatetruecolor( $width, $height ) Parameters: This function accepts two parameters as mentioned above and described below: $width: This parameter is used to s
2 min read
PHP fpassthru( ) Function
The fpassthru() function in PHP is an inbuilt function which is used to read data from a current position from a specified file until end of file and then write the result to the output buffer. The file which has to be read is sent as a parameter to the fpassthru() function and it returns the number of characters passed on success or FALSE on failu
2 min read
PHP | ImagickDraw getTextAlignment() Function
The ImagickDraw::getTextAlignment() function is an inbuilt function in PHP which is used to get the alignment applied when annotating with text. It helps to format the text by making it stick to left, right or middle. Syntax: int ImagickDraw::getTextAlignment( void ) Parameters: This function doesn’t accept any parameter. Return Value: This functio
2 min read
PHP | Ds\Sequence last() Function
The Ds\Sequence::last() function is an inbuilt function in PHP which is used to return the last element from the sequence. Syntax: mixed abstract public Ds\Sequence::last( void ) Parameters: This function does not accept any parameters. Return value: This function returns the last element from the sequence. Below programs illustrate the Ds\Sequence
1 min read
PHP | array_udiff_uassoc() Function
The array_udiff_uassoc() Function is an inbuilt function in PHP and is used for distinguishing between two or more array. The function computes the differences array by use of two user-defined functions with the additional index key. It compares both data and index by use of callback functions and returns the difference. Syntax : array_udiff_uassoc
5 min read
How to generate Json File in PHP ?
In this article, we are going to generate a JSON file in PHP by using an array. JSON stands for JavaScript object notation, which is used for storing and exchanging data. JSON is text, written with JavaScript object notation. Structure: {"data":[ { "sub_data1":"value1", "sub_data2":"value2","sub_data_n":"value n" }, { "sub_data2":"value2","sub_data
3 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
PHP | geoip_continent_code_by_name() Function
The geoip_continent_code_by_name() function is an inbuilt function in PHP which helps to generate a two-letter continent code(Each continent has assigned a two-letter code. For example - AF for Africa, AS for Asia, and many more). The function takes the hostname or IP Address as an argument and generates the two-letter continent code. Syntax : stri
1 min read
How to secure database passwords in PHP?
Most of the websites are providing sing up and login facility to the user. User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the database. Syntax password_hash(Password, PASSWORD_
2 min read
PHP | GmagickPixel setcolor() function
The GmagickPixel::setcolor() function is an inbuilt function in PHP which is used to set the color of the GmagickPixel object. Syntax: GmagickPixel GmagickPixel::setcolor( string $color ) Parameters:This function accepts a single parameter $color which holds the color. Return Value: This function returns GmagickPixel object on success. Exceptions:
1 min read
PHP Calendar Functions Complete Reference
The calendar extension contains a series of functions to represent the calendar date into a different format. The standard date is based on Julian Day Count. The date count starting from January 1st, 4713 B.C. is known as Julian Day Count. First, the date is converted into Julian Day Count and then converted into a calendar system. Example: The pro
2 min read
PHP | opendir() Function
The opendir() function in PHP is an inbuilt function which is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure. The opendir() function is used to open up a directory handle to be used in subsequent with
2 min read
PHP | cal_to_jd() Function
The cal_to_jd() function is an inbuilt function in PHP which is used to converts a specified date into Julian Day Count. The cal_to_jd() function calculates the Julian day count for a date in the specified calendar. This function supports CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH calendars.Syntax: int cal_to_jd( $calendar, $month, $day,
2 min read
PHP | stream_get_transports() Function
The stream_get_transports() function is an inbuilt function in PHP which is used to get the list of registered socket transports. This function returns the indexed array containing the name of all available socket. Syntax: array stream_get_transports( void ) Parameters: This function does not accept any parameter. Return Value: This function return
1 min read
When do we need Interfaces in PHP?
Interface are definitions of the public APIs that classes (implementing an interface) must implement. It is also known as contracts as an interface allows to specify a list of methods that a class must implement. Interface definition is similar to the class definition, just by changing the keyword class to interface.Example: PHP Code &lt;?php inter
3 min read
How to write Into a File in PHP ?
In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file has to close by using the PHP fclose() function. S
2 min read
PHP | Ds\Deque pop() Function
The Ds\Deque::pop() function is an inbuilt function in PHP which is used to remove the last element from Deque (if Deque is not empty) and return it. If Deque is empty then it throws an exception. Syntax: public Ds\Deque::pop( void ) : mixed Parameters: This function does not accept any parameter. Return Value: This function returns the removed las
2 min read
PHP | SimpleXMLElement children() Function
Pre-requisite: Read XML BasicsThe SimpleXMLElement::children() function is an inbuilt function in PHP which returns children of a given node in a SimpleXML object. Syntax: SimpleXMLElement SimpleXMLElement::children( $namespace, $is_prefix ) Parameter: This function accepts two parameters as mentioned above and described below: $namespace: It is op
3 min read
Javascript | JSON PHP
JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object into the JSON format is done by the given functio
7 min read
PHP | dir() (Get instance of the Directory)
The dir() function in PHP used to find the instance of a Directory class. This function read directory, which includes the following: The given directory is opened. The two properties handle and path of dir() are available. The handle property can be used with other directory functions such as readdir(), rewinddir(), closedir(). The path property i
2 min read
PHP | array_intersect_ukey() Function
The array_intersect_ukey() function is an inbuilt function in PHP which is used to compute the intersection of two or more array against keys with the help of user-defined function and the function return an array. The returned array is the first array, which is matching keys and present in all parameters is the final output. Syntax: array array_in
5 min read
PHP | is_numeric() Function
The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value. Syntax: bool is_numeric ( $var ) Parameters: The function accepts a single parameter which is mandatory and described below: $var: This inpu
2 min read
PHP | Imagick adaptiveSharpenImage() Function
The Imagick::adaptiveSharpenImage() function is an inbuilt function in PHP which provides an adaptive sharpen image feature to the image. The intensity of an adaptive sharpen image depends on dramatically decreased at the edge of the image. Syntax: bool Imagick::adaptiveSharpenImage ( $radius, $sigma, $channel ) Parameters: This function accepts th
1 min read
PHP | isset() Function
The isset() function is an inbuilt function in PHP which is used to determine if the variable is declared and its value is not equal to NULL. Syntax: bool isset( mixed $var [, mixed $... ] ) Parameters: This function accept one or more parameter as mentioned above and described below: $var: It contains the variable which need to check. $...: It con
2 min read
PHP | Coding Standards
PHP follows few rules and maintains its style of coding. As there are many developers all over the world, if each of them follows different coding styles and standards this will raise great confusion and difficulty for a developer to understand another developer's code. It will be very hard to manage and store the code for future reference. The cod
3 min read
PHP | ctype_print() Function
The ctype_print() Function in PHP used to check each and every character of a string are visible or not. If all characters of string are visible then returns TRUE , else if there are any control character then return FALSE. Control Character: A character that does not represent a printable character but serves to initiate a particular action. for e
2 min read
three90RightbarBannerImg