PHP Superglobals

PHP Superglobals are quite helpful in designing quality code with less complexity. In this article, we see different PHP superglobal variables.

Read Also: PHP Array Functions

PHP Superglobals

  • The superglobals, defined as array variables in PHP, make it easy to get information about the request.
  • They are a type of variable that is available from any part of the code.
  • The superglobals are accessed in any scope, file, class, or function.
  • Superglobals do not have fixed scope; they are available in all of them as they differ from local and global variables.
  • The PHP superglobals are sometimes referred to as automatic global or auto global.

There is a list of superglobal variables available in PHP that we are most likely to find useful in our daily tasks:

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

Let’s discuss some of these superglobal variables in detail.

$GLOBALS

PHP $GLOBALS is a superglobal variable that is useful to access the global variable from anywhere in the script. PHP stores all the global variables in the array $GLOBALS[]. It is an associative array that refers to variables defined in the global scope of the script.

Example

<?php 

$x = 300; 

$y = 200; 

function addition(){ 

    $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y']; 

} 

addition(); 

echo $z; 

?>

Output

50

In the above example, two global variables, $x and $y contain some value. Then a function addition() is defined to add the values of $x and $y and store in another variable $z, defined in the GLOBAL array.

$_SERVER

The $_SERVER superglobal variable stores the information about the headers, paths, and scripts locations. The web server creates the entries in the array.

Example

<?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>";

?>

$_REQUEST

The $_REQUEST superglobal variable is useful to collect data after submitting the HTML form. The $_REQUEST mostly comes into the picture because $_POST and $_GET perform the same task and are widely useful compare to $_REQUEST.

Example

<!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

$_REQUEST

$_POST

The $_POST superglobal variable is useful to collect data from the HTML form after submitting it. When the form uses the method ‘POST’ to transfer data, the data is not visible in the query string; this method maintains the security level. Sending data via POST is not secure.

Example

<!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

$_POST

$_GET

$_GET superglobal variable is useful to collect data from the HTML form after submitting it. When the form uses the method ‘GET’ to transfer data, the data is visible in the query string. Therefore the values are not hidden. $_GET superglobal array variable stores the values that come in the URL. Please do not send any sensitive data via the URL as it will remain in the history of the system and be visible to anyone who uses that browser.

Example

<!DOCTYPE html> 

<html> 

<head> 

<title></title> 

</head> 

<body> 

<form method="get" action="<?php echo $_SERVER['PHP_SELF'];?>">

Name: <input type="text" name="name">

Message: <input type="text" name="message">

<input type="submit" value="Send">

</form>   

<?php

if ($_SERVER["REQUEST_METHOD"] == "GET"){   

    $name = $_GET['name'];

    $message= $_GET['message'];

    if (empty($name)){

        echo "Name is empty";

    }elseif (empty($message)){

       echo "Message is empty";

    }else{

        echo "Hello $name, here is your message: $message";

    }

}

?>

</body> 

</html>

Output

$_GET

$_SESSION

To use sessions, we must include session_start() at the top of your scripts to allow sessions to be utilized.

<?php

        Session_start();

        $_SESSION[‘name’]=’Suman’;

 ?>

Setting a session variable is similar to setting any other variable.

$_SESSION["myVar"] = "myVal";

Once a session is set, it can easily access throughout the script via the $_SESSION superglobal.

<?php

if(isset($_SESSION[‘name’]))

        echo htmlspecialchars($_SESSION[‘name’]);

?>

We can destroy session variables using the unset function or by using session_destory(). It will destroy the entire session; the session variables will no longer exist.

$_COOKIE

Cookies are variables that contain data and are stored on the client’s computer.

setcookie("myVar", "myVal", time() + 3600);

In the example above, a name is specified for the cookie, a value is given, and then an expiration time is given.

The $_cookie accesses in the same way as the others.

echo $_COOKIE["myVar"]; // returns "myVal"

To destroy a cookie, setcookie must be called again, but the expiration time is set to any time in the past.

setcookie("myVar", "", time() - 1);

var_dump($_COOKIE["myVar"]); // returns null

This will unset the cookies and remove them from the client’s computer.

$_ENV

The $_ENV Superglobal represents data available to a PHP script from the environment in which PHP is running.

These variables are imported into PHP’s global namespace from the environment under which the PHP parser is running. Please see your shell’s documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or a CGI processor.

Anything stored within $_ENV is from the environment in which PHP is running in.

$_FILES

$_FILES superglobal variable is useful for uploading files. It is a two-dimensional associative array of items that are being uploaded via the HTTPP POST method. It consists of different attributes, such as:

                                Attributes                            Description

[name]

Name of the file
[Size]It represents the size of the file
[type]Type of the file(like pdf,zip,jpeg…etc)
[tmp_name]A Temporary address where the file is located before uploading a file.
[error]

Types of errors occurred when the file is uploading.

  • $_FILES[input-field-name][name]
  • $_FILES[input-field-name][tmp_name]
  • $_FILES[input-field-name][size]
  • $_FILES[input-field-name][type]
  • $_FILES[input-field-name][error]

Conclusion

We hope you have had a complete understanding of PHP Superglobals.

Happy Coding 🙂

Leave a Reply

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