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:
- $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:
- 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:
- 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:
<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>
$GLOBALS['sq']=$GLOBALS['a']*$GLOBALS['a'];
- $_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:
- Let us see an example:
- Write the following code in index.php file:
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. |
<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>
- $_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>
$nm=$_REQUEST['name'];
echo "Welcome <strong>".$nm."</strong>";
- $_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>
echo "<strong>".$nm." is $age years old.</strong>";
- $_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>
<a href="picture.php?name=QutubMinar&city=Delhi"><img src="qutubminar.jpg" alt="Qutubminar" height="200" width="200"/></a>
<html> <head> <title>QutubMinar</title> </head> <body bgcolor="cyan"> <?php $nm=$_GET['name']; $city=$_GET['city']; echo "<h1> This is ".$nm." of ".$city."</h1><br><br>"; ?> <img src="qutubminar.jpg" alt="QutubMinar" height="400" width="500"/> </body> </html>
- $_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"> <input type="submit" value=" OK "/> </form> </body> </html>
$_SESSION['uname']="Brad123";
<html> <head> <title>WELCOME</title> </head> <body bgcolor="pink"> <?php session_start(); $unm=$_SESSION['uname']; echo "<h1> WELCOME ".$unm."</h1>"; ?> <img src="life.jpg" alt="message" height="400" width="400"/> </body> </html>
$unm=$_SESSION['uname'];
- $_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> <input type="submit" value=" SEND "/> </form> </body> </html>
$time=time()+60*60*24*30;
<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>
$_COOKIE[‘cookie_name’];
- $_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> <input type="submit" value="Submit"/> </form> </body> </html>
<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>
- $_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.
if($_FILES["file"]["error"]>0)
$_ENV[“variable_name”];
<?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.