Introduction

  • The concept of Super global variables was introduced in/after PHP 4.1.0.
  • The superglobal variables are also known as Global Variables/Automatic Globals.

Definition

  • Super global variables are pre-defined, built-in variables & are of global scopes and hence always accessible from any function, class, file, etc.

Features

  • These variables can be used wherever needed i.e., they do not need to be declared, nor do they need to be marked with global in functions.
  • They are used for a variety of purposes by the developers as per the need of the program to access globally anywhere on the web document’s page.
  • While using global variables can be convenient, but it can also make our code more difficult to debug and maintain. Hence, it’s generally a good idea to limit the use of global variables and instead use local variables and function parameters whenever possible.

Examples

  • There are 9 PHP super global variables. These are:-
    • $_GET
      • $_GET is a Super global variable in Php that is used to collect data that is sent to the server via HTTP GET method.
      • It retrieves the values of the variables that are passed through the URL.
      • In Php, $_GET is also used to retrieve values from the HTML design page that have been sent to the PHP script through the URL query string. The values in the query string are passed as key/value pairs, where the key is the name of the variable, and the value is the data of the variable.
      • The values passed (using $_GET) through the URL are visible to the user and can be manipulated which is considered as insecure. Hence, $_GET without proper validation can be a security risk, as it allows attackers to manipulate the data being sent to the server. It is recommended to use input validation and sanitization techniques to ensure that the data received via $_GET is safe to use otherwise, it is suggested that use $_POST in place of $_GET.
      • Syntax

$value = $_GET[‘variable_name’];

      • For example – 

<?php
       $name1 = $_GET[‘name’];
       $age1 = $_GET[‘age’];
       echo ” $name1, is $age1 years old!”;
?>
Here, the ‘name’ and ‘age’ may be the key name of a URL of a Php script (such as  “http://example.com/page1.php?name=Robert & age=33“) or an Html script page.

    • $_POST
      • $_POST is also a Super global variable in Php that is used to collect data that is sent to the server via the HTTP POST method.
      • It retrieves the values of the variables that are submitted through an HTML form with the method attribute set to “POST”.
      • Syntax :

$value = $_POST[‘variable_name’];

      • For Example:

<form action=”page1.php” method=”post”>
      User Id: <input type=”text” name=”uname”>
      Password: <input type=”password” name=”pass”>
      <button type=”submit”>Submit</button>

      $username = $_POST[‘uname’];
      $password = $_POST[‘pass’];
</form> 

    • $_REQUEST
      • $_REQUEST is also a Php Super global variable that contains the contents of $_GET, $_POST, and $_COOKIE arrays.
      • It is used to collect data sent to the server via HTTP request methods like GET, POST, and COOKIES.
      • Since $_REQUEST is a combination of both $_GET and $_POST data, it can sometimes make debugging more difficult. In general, it is better to use $_POST directly, depending on the specific needs of the developer code.
      • Syntax :

$value = $_REQUEST[‘variable_name’];

      • For example

<form action=”page1.php” method=”post”>
      User Id: <input type=”text” name=”uname”>
      Password: <input type=”password” name=”pass”>
      <button type=”submit”>Submit</button>

      $username = $_REQUEST[‘uname’];
      $password = $_REQUEST[‘pass’];
</form> 

  •  
    • COOKIE & $_COOKIE

Cookie

      • Cookies are small pieces of data that are sent from a website and stored in the user’s browser and are often used to store information about the user’s preferences or to keep the user logged in.
      • Cookies are used to keep track of user sessions, preferences, language settings, and other information.
      • It’s recommended to only store small amounts of data in cookies because cookies can be manipulated by attackers.

$_Cookie

      • $_COOKIE is also a Super global variable in Php that is used to retrieve the values of cookies that are stored on the client side (i.e. in the user’s browser).
      • Syntax:

$value = $_COOKIE[‘cookie_name’];

      • Methods of Cookie:
        • In Php, several methods can be used to work with cookies.
        • Here are some of the most commonly used cookie methods: –
          • To Retrieve a cookie value($_COOKIE):
            • To retrieve a cookie value, the $_COOKIE Super global variable is used.
            • For example:

To retrieve a cookie value($uname1) having named “uname”, we would use-

$uname1 = $_COOKIE[‘uname’];

          • To Set a cookie value (setcookie()):
            • This function is used to set a cookie with a name and a value.
            • It takes up to seven parameters, but the name and value are the only required ones.
            • To set a cookie value, we use the setcookie() function in PHP.
            • The setcookie() function takes several parameters, including the name of the cookie, its value, expiration time, path, and domain.
            • Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

Where,

              • name: The name of the cookie.
              • value: The value of the cookie.
              • expire: The expiration time of the cookie, specified as a Unix timestamp. If omitted, the cookie will expire at the end of the session.
              • path: The path on the server where the cookie will be available. If set to ‘/’, the cookie will be available to the entire domain.
              • domain: The domain where the cookie is available. If set to ‘.example.com’, the cookie will be available to all subdomains of example.com.
              • secure: Indicates whether the cookie should be sent over a secure HTTPS connection. If true, the cookie will only be sent over HTTPS.
              • httponly: Indicates whether the cookie can only be accessed through the HTTP protocol. If true, the cookie cannot be accessed by JavaScript.
            • For example:

[i] setcookie(‘uname’, ‘Robert’, time() + 3600, ‘/’, ‘example.com’, true, true);

(The above code sets a cookie named ‘uname’ with a value of ‘Robert’ that will expire in 1 hour, is available to the entire domain ‘example.com’, is sent over HTTPS only, and cannot be accessed by JavaScript.)

[ii] setcookie(‘uname’, ‘Robert’, time()+3600, ‘/’);

(The above code sets a cookie named “uname” with the value “Robert”, and an expiration time of 1 hour (3600) from the current time. The cookie is also set to be accessible from the root directory (/) of the website.)

          • To check the existence of a cookie (isset()):
            • To check if a cookie exists, the isset() function along with the name of the cookie is used.
            • For Example:

if (isset($_COOKIE[‘uname’])) {
echo “The cookie exists”;
} else {
echo “The cookie does not exist.”;
}

          • To Delete a cookie (isset()):
            • To delete a cookie, we can set its value to an empty string using setcookie() method and set the expiration time to a time in the past.
            • For Example:

setcookie(‘uname’, ‘ ‘, time() – 3600, ‘/’);

(The above code deletes the “uname” cookie by setting its string value to an empty string(optional) and setting the expiration time to 1 hour in the past(-3600)[compulsory]. The cookie is also set to be accessible from the root directory of the website.)

  •  
    • SESSION & $_SESSION

Session:

      • In web development, a session refers to the period during which a user interacts with a specific web application.
      • A session begins when a user logs in or starts using the application and ends when they log out or close the application.
      • Sessions can also be used to manage user authentication and security. 
      • Session management can be implemented using various techniques and technologies, such as cookies, URL rewriting, or server-side storage. Web developers need to ensure that sessions are properly managed and secured to protect user privacy and prevent attacks such as session hijacking or session fixation.
      • Session ID : During a session, the web application maintains a unique identifier, known as a session ID, that is associated with the user’s activity. This session ID allows the web application to keep track of the user’s actions and data, such as the items in their shopping cart, the pages they have visited, or their preferences.

$_Session:

      • $_SESSION is a Super global variable that is used to store session data in Php.
      • When a user visits a website, Php creates a unique session ID for that user, which is used to track their activity during their session.
      • The $_SESSION variable is used to store and retrieve data that is associated with the current user’s session. For example, if a user logs in to a website, their user ID and other relevant information may be stored in the $_SESSION variable, so that it can be accessed on subsequent pages or requests during the same session. The session data is stored on the server, so it can’t be modified or accessed by the user. 
      • In PHP, the $_SESSION Super global variable provides several built-in methods that allow the user to manage session data. Some of the most commonly used $_SESSION methods are :

        session_start(): This function starts a new or resumes an existing session. It should be called at the beginning of each page that needs to access session data. It must be called before any session data is accessed or modified.

   session_id(): This function returns the current session ID. It can also be used to set a new session ID.

   session_regenerate_id(): This function generates a new session ID and deletes the old session data. It can be used to prevent session fixation attacks.

  session_destroy(): This function is used to destroy the current session, including all session variables and the session cookie.

  session_name(): This function is used to get or set the name of the current session.

  session_unset(): This function removes all session variables.

session_save_path(): This function is used to get or set the path where session data is stored.

 session_status(): This function returns the current session status.

session_set_cookie_params(): This function is used to set the parameters for the session cookie, such as the cookie lifetime, domain, and path.

  • $GLOBALS
    • In Php, $GLOBALS is a superglobal variable that allows access to all global variables from anywhere in the PHP script.
    • It is an associative array where the keys are the names of the global variables and the data are the values of those variables.
    • It is believed that the use of global variables can make the code less readable and harder to debug and maintain, especially in large projects, and can introduce unexpected behavior if not used carefully. Hence, it is generally considered that the best practice is to avoid relying too heavily on using global variables when possible, and instead pass variables as function arguments or use object-oriented programming techniques(use more structured approaches such as classes and functions to encapsulate and manage data) is better.
    • When a variable is declared as global within a function, it can be accessed using $GLOBALS array from any other function or part of the code.
    • For example – 

<?php
     $x = 10;
     $y = 20;

   function add() {
     $GLOBALS[‘z’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
   }

   add();        //calling of function
   echo $z;         // Outputs 30
?>

      • Here, the add() function uses the $GLOBALS keyword to access the defined global variables $x and $y, and then sets the value of $z to the sum of $x and $y. Here, the echo statement is outside the function and even outputs the value of $z.

—————————  OR  —————————

<?php
       $Var = “Hello, India”;

       function msg() {
       echo $GLOBALS[‘Var’];
       }

       msg();    //calling of function results “Hello India”
?>

In this example, the $Var the variable is defined in the global scope of the script, and the msg() the function is used to access it using $GLOBALS

———————-  OR  ———————-

<?php
     $x = 100;
     $y = 200;

     function add() {
          global $x, $y;
          $sum = $x + $y;
          return $sum;
     }

     echo add();       // Output: 300
?>

In the above code, the variables $x and $y are declared as global variables inside the add() function using the global keyword. Then, the add() function uses $GLOBALS array to access the values of $x and $y.

———————-  OR  ———————-

<?php
     $x = 100;
     $y = 200;
     $z = $GLOBALS[‘x’] + $GLOBALS[‘y’];
     echo $z;      // Output: 300
?>

In the above code, $z is assigned the value of $x + $y, which is accessed using $GLOBALS array.

———————-  OR  ———————-

<?php
     $x = 100;
     $y = 200;

function add() {
     global $x, $y;
     $sum = $x + $y;
     return $sum;
}

echo $GLOBALS[‘x’];       // Output: 100
echo $GLOBALS[‘y’];      // Output: 200
echo add();                   // Output: 300
?>

The above example explains that $GLOBALS acts as an associative array that stores all global variables as keys and their data as values. In this, the global variables $x and $y are defined outside the add() function, and then the add() function uses the global keyword to make these variables available inside the function. The add() function then calculates the sum of $x and $y returns it.

  • $_SERVER
    • $_SERVER is a superglobal variable in PhP that contains information about the server and execution environment.
    • It is an associative array that contains various elements such as HTTP headers, paths, the request method, query string, client IP address, and script locations.
    • $_SERVER is a powerful tool for accessing and using information about the Server and environment in which our PHP code is running. However, it is suggested that be careful not to rely too heavily on this variable, as some of the information it contains can be spoofed or manipulated by malicious users.
    • Some of the common elements in $_SERVER superglobal include:
      • $_SERVER['PHP_SELF']: It gives the filename of the currently executing script, relative to the document root.
      • $_SERVER['SERVER_SOFTWARE']: It gives the name and version of the server software that is running on the server.
      • $_SERVER['SERVER_NAME']: It gives the name of the server host under which the current script is executing.
      • $_SERVER['REQUEST_METHOD']: It gives the HTTP request method used to access the page (e.g. GET, POST, HEAD, PUT).
      • $_SERVER['REQUEST_URI']: It gives the URI of the current request, including any query string parameters i.e., used to get the current URL of the page that is being accessed.
      • $_SERVER['QUERY_STRING']: It gives the query string, if any, via which the page was accessed.
      • $_SERVER['HTTP_USER_AGENT']: It gives the user agent string sent by the user’s browser.
      • $_SERVER['REMOTE_ADDR']:  It gives the IP address of the user who accessed the page.
    • For example –

<?php
     echo $_SERVER[‘PHP_SELF’];
?>

The above code will output the name of the current script file, such as /index.php or /about.php, depending on which script is being executed.

———————-  OR  ———————-

<?php
     if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {
               // Code to handle the form submission
     } else {
               // code to show form
     }
?>

The above code checks if the HTTP request method is post, indicating that a form submission was made, and handles the submission accordingly. In other words, it is used to determine which HTTP request method was used to access the current page.

  • $_FILES 
    • $_FILES is a built-in PHP superglobal variable that is used to handle file uploads in a web application. When a file is uploaded to the server, PhP populates the $_FILES superglobal with information about the uploaded file, such as its name, type, size, and temporary location.
    • $_FILES is an associative array that contains one or more file upload elements/information details, with each element having the following keys:
      • name: The original name of the file on the client machine.
      • type: The MIME type of the file, as provided by the client browser.
      • size: The size of the file in bytes.
      • tmp_name: The temporary filename of the uploaded file, as stored on the server.
      • error: The error code associated with the file upload, if any.
    • For example – The following code of HTML form allows a user to upload a file: 

<form action=“upload.php” method=”post” enctype=”multipart/form-data”>
     <input type=”file” name=”file1″>
     <input type=”submit” value=”Upload”>
</form>

It is suggested that we must set the enctype the attribute of the form to multipart/form-data to allow file uploads, and there are various security considerations involved in handling file uploads, such as validating file types and sizes and preventing file upload exploits.

Using the PHP script that handles the form submission, we can access the uploaded file information from $_FILES as below :

<?php
     if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {
          $file = $_FILES[‘file1’];
          $filename = $file[‘name’];
          $tempname = $file[‘tmp_name’];
          $filesize = $file[‘size’];
          $filetype = $file[‘type’];
          $fileerror = $file[‘error’];

          // To move the uploaded file to a permanent location, we use
          move_uploaded_file($tempname, “/path/to/uploaded/files/$filename”);
          }

?>

—————  OR  —————

<?php
if ($_FILES[‘file1’][‘error’] === UPLOAD_ERR_OK) {
    $tmp_name = $_FILES[‘file’][‘tmp_name’];
    $name = basename($_FILES[‘file’][‘name’]);
    $upload_path = ‘/path/to/upload/directory/’ . $name;
    move_uploaded_file($tmp_name, $upload_path);
    echo “File uploaded successfully!”;
} else {
     echo “Error uploading file.”;
}
?>

In the above code, the if statement checks if the file was uploaded successfully by checking the UPLOAD_ERR_OK constant against the error element in $_FILES['file1']. If the file was uploaded successfully, the script moves the temporary file to the specified upload directory using move_uploaded_file().

Here, $_FILES is only populated for POST requests that contain file uploads. If we try to access $_FILES in a GET request or a POST request without a file upload, it will be empty.

  • $_ENV
    • $_ENV is a PHP superglobal variable that contains a map of environment variables passed to the current PHP script. Environment variables are typically set by the operating system or web server and can contain information such as the current user, the current working directory, and database connection details.
    • $_ENV is an associative array, where the keys are the names of the environment variables and the data are their corresponding values.
    • We can access a specific environment variable using its name as the key, like $_ENV['USERNAME'] or $_ENV['DATABASE_URL'].
    • $_ENV is only available when PHP is running as a CGI or FastCGI process. If PHP is running as an Apache module, environment variables are available in the $_SERVER superglobal variable instead.

Loading

Categories: Php Theory

0 Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.