PHP Superglobals

Today we are going to learn a new concept called superglobals in this PHP Superglobals tutorial.

  • What are Superglobals?
    • PHP has predefined some array variables.
    • These variables are accessible anywhere in a script, anytime. I mean these variables are always accessible regardless of the scope, because they are defined to be accessed globally everywhere in all scopes.
    • 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.
    • The PHP superglobal variables are as follows:
      • $GLOBALS
      • $_SERVER
      • $_REQUEST
      • $_GET
      • $_POST
      • $_SESSION
      • $_COOKIE
      • $_FILES
      • $_ENV
    • Let us see all the superglobal array variables one by one:
    1. $GLOBALS:
      • $GLOBALS is a superglobal variable which stores all the variables declared in a script and can be used to access any variable anywhere in the script.
      • PHP stores all the global variables in array $GLOBALS[].
      • The array has an index which holds the global variable name, using which it can be accessed.
      • Let us see an example:
      • To demonstrate the examples create a new folder named superglobals in the htdocs folder in xampp folder. Then open a new notepad++ document and save it as index.php in the newly created superglobals folder.
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	$a=10;
        	
        	function square()
        	{
        		$GLOBALS['sq']=$GLOBALS['a']*$GLOBALS['a'];
        	}
        	
        	square();
        	echo "<strong>Square of $a = $sq</strong>";
        ?>
        </body>
        </html>
        
      • In the code above, we have declared a global variable $a assigned with value 10.
      • Then a function square() is defined to calculate the square of value in global variable $a.
      • As we know that the variable $a will not be accessed in the function square() as it is not declared inside it, we make it possible by accessing it using the $GLOBALS array variable.
      • The value of $a is accessed and calculated as shown in the following statement:
      • $GLOBALS['sq']=$GLOBALS['a']*$GLOBALS['a'];
      • As the function square() is called, it calculates the square of 10.
      • Then obtained square can be displayed directly as the variable $sq is also present in $GLOBALS array variable.
      • The output is shown below:
      • $GLOBALS_output
        fig 1

    2. $_SERVER:
      • $_SERVER is a PHP super global variable which stores information about headers, paths and script locations i.e. it stores information about web and the requests made to it.
      • Some elements are used to get the information from the superglobal variable $_SERVER.
      • There are many elements of information used in $_SERVER variable. Some of them are listed below:
      • Element Description
        $_SERVER[‘PHP_SELF’] Returns the filename of the currently executing script.
        $_SERVER[‘SERVER_ADDR’] Returns the IP Address of the host server.
        $_SERVER[‘SERVER_NAME’] Returns the name of the host server.
        $_SERVER[‘QUERY_STRING’] Returns the query string if the page is accessed via a query string.
        $_SERVER[‘REQUEST_TIME’] Returns the timestamp of the start of the request.
      • Let us see an example:
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	echo "*current file name: ".$_SERVER['PHP_SELF'];
        	echo "<br><br>";
        	echo "*server name: ".$_SERVER['SERVER_NAME'];
        	echo "<br><br>";
        	echo "*Request Method: ".$_SERVER['REQUEST_METHOD'];
        	echo "<br>";
        	
        ?>
        </body>
        </html>
        
      • 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.
      • Then we get the method of transfer of data using ‘REQUEST_METHOD’ element.
      • The output is shown below:
      • $_SERVER_output
        fig 2

    3. $_REQUEST:
      • $_REQUEST is a superglobal variable used to collect data after submitting a HTML form.
      • $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.
      • Let us see an example for it. $_REQUEST can result to security risks.
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	<!--demonstration of $_REQUEST-->
        	<form name="greet" method="post" action=<?php echo $_SERVER['PHP_SELF'];?>>
        	<label for="name">Please enter your name: </label>
        	<input name="name" type="text">
        	<input type="submit" value="Submit">
        	</form>
        	
        	<?php
        		$nm=$_REQUEST['name'];
        		echo "Welcome <strong>".$nm."</strong>";
        	?>
        </body>
        </html>
        
      • In the above code we have created a form that takes the name as input from the user and greets Welcome to him/her when the user clicks on 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 as shown in the statement
        $nm=$_REQUEST['name'];
      • Then it is displayed using the echo statement as follows:
      • echo "Welcome <strong>".$nm."</strong>";
      • The output is shown below:
      • $_REQUEST_output
        fig 3

    4. $_POST:
      • $_POST is a super global variable used to collect data from the HTML form after submitting it, when the method used to transfer data is “POST”.
      • When form uses method post to transfer data, the data is not visible in the query string, i.e. security levels are maintained in this method.
      • Let us see an example:
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	<!--demonstration of $_POST-->
        	<form name="postm" 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">
        	</form>
        	
        	<?php
        	$nm=$_POST['name'];
        	$age=$_POST['age'];
        	
        	echo "<strong>".$nm." is $age years old.</strong>";
        	?>
        	
        </body>
        </html>
        
      • 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 he/she submit’s 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.
      • These values are then displayed in a sentence as shown below:
      • echo "<strong>".$nm." is $age years old.</strong>";
      • The output is shown below:
      • $_POST_output
        fig 4

    5. $_GET:
      • $_GET is a super global variable used to collect data from the HTML form after submitting it, when the method used to transfer data is “GET”.
      • 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.
      • Let us see an example:
      • Write the following code in index.php file:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	<!--demonstration of $_GET-->
        	<h1><font color="red">Historic Monument</font></h1>
        	<a href="picture.php?name=QutubMinar&city=Delhi"><img src="qutubminar.jpg" alt="Qutubminar" height="200" width="200"/></a>
        	
        </body>
        </html>
        
      • We are actually seeing half of the logic just now, let us understand the above code and then see the rest of the logic.
      • In the above code we have created a hyperlink image of QutubMinar which will take us to picture.php page and with it will also take the paramerters name=”QutubMinar” and city=”Delhi”.
      • That is when we click on the small image of QutubMinar 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 (?).
      • The parameters are then written as a key-value pair following the question mark (?) as specified in the following statement:
      • <a href="picture.php?name=QutubMinar&city=Delhi"><img src="qutubminar.jpg" alt="Qutubminar" height="200" width="200"/></a>
        
      • Here the parameter name=QutubMinar 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=Delhi is added using ampersand after the name parameter.
      • Now after clicking on the image of QutubMinar we want the picture.php page to be displayed with the value of parameter displayed along with it.
      • So let us write the code for it in picture.php page.
      • <html>
        <head>
        <title>QutubMinar</title>
        </head>
        <body bgcolor="cyan">
        
        	<?php
        		$nm=$_GET['name'];
        		$city=$_GET['city'];
        		echo "<h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is ".$nm." of ".$city."</h1><br><br>";
        		
        	?>
        	<img src="qutubminar.jpg" alt="QutubMinar" height="400" width="500"/>
        	
        </body>
        </html>
        
      • Here, we received the values of the parameters name and city using the super global array variable $_GET and stored it in variables $nm and $city respectively.
      • These are then displayed using echo statement.
      • A magnified image of QutubMinar is shown below.
      • First let us see the output when index.php page is run.
      • $_GET_output_1
        fig 5

      • Now when we click on the hyperlink image of QutubMinar, we get the following output:
      • $_GET_output_2
        fig 6

      • You can see that the address bar of the browser contains the parameters name and city passed in the hyperlink.
      • These are retrieved using $_GET global variable and displayed in the string This is QutubMinar of Delhi.
    6. $_SESSION:
      • $_SESSION is a predefined super global array variable which is used to remember the state of a user and the values he wants to retrieve throughout his session.
      • Previously each request to the server was an individual request.
      • HTML is a stateless protocol. It means it cannot remember the pages visited by user in a website.
      • But today we use websites where user wants the site to remember the pages he/she has visited or what did he do previously. For example shopping sites.
      • Sessions are designed for the same reason. Sessions remember whatever user does from the period of logging in to logging out.
      • The $_SESSION array variable is used to store values from any page and retrieve them in any other page without passing them in a URL.
      • Before storing any variable a session is to be started using session_start(); statement.
      • Let us see an example:
      • Write the following code in index.php page:
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        
        //demonstration of $_SESSION 
        session_start();    //to start the session
        echo "<h1>Click on 'OK' button and take username 'Brad123' to welcome page.</h1>";
        $_SESSION['uname']="Brad123";
        ?>
        
        <form method="post" action="welcome.php">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="  OK  "/>
        </form>
        
        </body>
        </html>
        
      • In the above code, we have started the session using session_start(); statement.
      • An instruction to click on OK button is given to take the string Brad123 to welcome page.
      • The OK button is created in the html form.
      • The string Brad123 is stored in the super global array variable $_SESSION using the following statement
      • $_SESSION['uname']="Brad123";
      • Now see the code written in welcome.php file:
      • <html>
        <head>
        <title>WELCOME</title>
        </head>
        <body bgcolor="pink">
        
        	<?php
        		session_start();
        		$unm=$_SESSION['uname'];
        		echo "<h1> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WELCOME ".$unm."</h1>";
        		
        	?>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="life.jpg" alt="message" height="400" width="400"/>
        	
        </body>
        </html>
        
      • Here, in the welcome.php file again to use session we started the session using session_start(); statement.
      • We access the value of uname stored in $_SESSION global variable using the statement
      • $unm=$_SESSION['uname'];
      • It is then displayed using echo statement.
      • Next an image is displayed just for the sake of decorating the page.
      •   is the non breakable space used to print the blank space.
      • The global variable $_SESSION can access any variable throughout the session i.e. it can access variables related to a user in any page of the application till his/her session is on.
      • The output of code written in index.php file is shown below:
      • $_SESSION_output_1
        fig 7

      • When we click on the OK button, we are taken to welcome.php page and there we access the string Brad123 as shown below.
      • $_SESSION_output_2
        fig 8

      • The Brad123 string is accessed using $_SESSION global variable.
    7. $_COOKIE:
      • $_COOKIE is a super global array variable used to retrieve the value of a cookie.
      • Cookie is a small file created by a server to identify a user.
      • Whenever a user requests for some information on an internet, the request goes to a server. If the user has connected to that server for first time, the server identifies his information and creates a small file with an identification number given to the user and appends it to the response send to the user and is stored in user’s computer.
      • After this whenever the user sends a request to that server, it carries the cookie file with it, due to which the server sends a response without again checking the server authentication.
      • Let us see how a value in a cookie file is retrieved using $_COOKIE global variable.
      • We will create a cookie in index.php file and retrieve it in cookie.php file. So consider index.php file as a server and cookie.php file as a user PC.
      • Write the following code in index.php file:
      • <?php
        	$time=time()+60*60*24*30;
        	setcookie("ID","Daniel456757*#",$time);
        ?>
        <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body bgcolor=”orange”>
        	<!--demonstration of $_COOKIE-->
           <h4>Sending a Cookie</h4>
        	<form method="post" action="cookie.php">
        	<br><br><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        		<input type="submit" value=" SEND "/>
        	</form>
        </body>
        </html>
        
      • In the above code, we have created a cookie using the setcookie() function.
      • Remember that the setcookie() function is to be written above the html tag always.
      • It takes 7 parameters, name of the cookie, value of the cookie, expiration time of the cookie, path of the cookie on server where it is available, domain on which the cookie is present, secure which indicates that the cookie should transmit only on the secure https connection from the user and httponly when true the cookie will be accessible only through HTTP protocol.
      • Among all these parameters only the name is mandatory and the rest are optional.
      • We have created a cookie with name ID, value Daniel456757*# and expiration time of 1 month.
      • The time is calculated as shown in the following statement
      • $time=time()+60*60*24*30;
      • Here, we get the current time using the time() function. To increase the expiration period by 1 month we added the current time with (60 sec * 60 min * 24 hours * 30 days).
      • Next we created a submit button with name SEND in a form, which when clicked will take us to cookie.php page.
      • Now let us write the code in cookie.php page to receive the cookie value:
      • <html>
        <head>
        <title>WELCOME</title>
        </head>
        <body bgcolor="orange">
        
        	<?php
        		if(isset($_COOKIE['ID']))
        			echo "<h1>Welcome! your identification number is =  ".$_COOKIE['ID']."</h1><br>";
        		else
        			echo "You don't have identification number.<br>";
        	?>
        	
        	
        </body>
        </html>
        
      • In the above code we try to receive the cookie value sent from index.php page.
      • The function isset() is used to check whether the value for the cookie is set or not.
      • The cookie value is accessed using the global array variable $_COOKIE as shown below:
      • $_COOKIE[‘cookie_name’];
      • In the above code we have accessed it as $_COOKIE[‘ID’]; since name of our cookie is ID.
      • The output of index.php page is shown below:
      • $_COOKIE_output_1
        fig 9

      • When we click on SEND button we are taken to the cookie.php page as shown below:
      • $_COOKIE_output_2
        fig 10

      • The value of cookie ID is displayed in the above figure.
    8. $_FILES:
      • $_FILES is a super global array variable used to get information of the upload files to the server.
      • We can check whether the file uploaded has been successfully uploaded or not.
      • The details of the file can also be retrieved using $_FILES variable.
      • Let us learn it with an example.
      • In the example we will upload the file from index.php page and will retrieve its information in file.php page.
      • Write the following code to upload the file in index.php page.
      • <html>
        <head>
        <title>PHP Superglobals</title>
        </head>
        <body>
        <?php
        	<!--demonstration of $_FILES-->
        	<h1>Upload an Image:</h1>
        	<form method="post" action="file.php" enctype="multipart/form-data">
        		<label for="file">Upload an image:</label>
        	<input type="file" name="file" id="file"/><br><br>
        	&nbsp;<input type="submit" value="Submit"/>
        	</form>
        
        </body>
        </html>
        
      • In the above code we have created a form to upload the file.
      • The form has post method and it will take the form data to file.php page as stated in action attribute of the form.
      • The form has one more attribute called enctype that has value multipart/form-data.
      • The attribute enctype indicates the encryption type and its value multipart/form-data converts the file data to binary format.
      • The input type to accept a file from user is file. It gives a browse button to browse the file.
      • When we click on the browse button an open file dialog appears, which allows us to select the desired file.
      • We have also included a submit button to submit the form.
      • To know whether our file has been uploaded or not, we have to write the following code in file.php page.
      • <html>
        <head>
        <title>File</title>
        </head>
        <body>
        
        	<?php
        		if($_FILES["file"]["error"]>0)
        		{
        			echo "Error : ",$_FILES["file"]["error"]."<br>";
        		}
        		else
        		{
        			echo "File Uploaded Successfully!<br><br>";
        			echo "File details:<br>";
        			echo "File name: ".$_FILES["file"]["name"]."<br>";
        			echo "File type: ".$_FILES["file"]["type"]."<br>";
        			echo "File size: ".$_FILES["file"]["size"]."<br>";
        			
        		}
        	?>
        	
        	
        </body>
        </html>
        
      • We have certain parameters used with $_FILES to know information about the file such as type, name, size, error, temp_name etc.
      • While including these parameters, first the input type for uploading the file i.e. file is used and then one of the above parameters are used in the array notation.
      • They are shown below:
        • $_FILES[“file”][“name”] – gives name of the uploaded file.
        • $_FILES[“file”][“type”] – gives type of the uploaded file.
        • $_FILES[“file”][“size”] – gives size in bytes of the uploaded file.
        • $_FILES[“file”][“error”] – if any error occurs during uploaded file, it gives the error code.
        • $_FILES[“file”][“tmp_name”] – gives the temporary name of the file copy stored on server.
      • In the above code we have checked for the error while uploading the file in the if statement as shown below:
      • if($_FILES["file"]["error"]>0)
      • Here, if the error code is greater than zero then some error has been occurred during file upload and it will print the error code.
      • But if the file has uploaded successfully, the condition in if statement will evaluate to false and details of file will be displayed.
      • The output of index.php file is shown below:
      • $_FILES_output_1
        fig 11

      • Now when we select a file and click on submit button, we will get the following output.
      • $_FILES_output_2
        fig 12

    9. $_ENV:
    10. $_ENV helps in obtaining/accessing the environment variables from the web server.
    11. Environment variables in PHP are those variables that allow the script to obtain certain information dynamically from server. It supports the script flexibility in a changing server environment.
    12. The syntax to access any environment variable using $_ENV is given below:
    13. $_ENV[“variable_name”];
    14. For example we can access a temp_pwd variable as follows:
    15. <?php
      	echo “Temporary Password: ”.$_ENV[“temp_pwd”];
      ?>

Among these super global array variables, the variables $_GET, $_POST,$_SERVER, $_SESSION are used the most. The $_REQUEST variable does the work of $_GET, $_POST and $_COOKIE but its use is avoided because it may lead to security problems.

Thus we learned all the super global variables in this PHP Superglobals tutorial.

Previous articlePHP Functions
Next articlePHP Array Operations

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -