Skip to main content

PHP Global Variables - Superglobals

By SamK
0
0 recommends
Category(s)
Topic(s)

There are some predefined variables in PHP, which are known as superglobals. These variables are always accessible, which means that they can be accessed inside any function, class, or file without requiring any special actions.

The PHP superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_COOKIE
  • $_FILES
  • $_SESSION
  • $_ENV

PHP $GLOBALS

$GLOBALS is an array that holds all global variables.

Global Variables

To use a global variable inside a function, you need to either declare it as global with the global keyword or reference it using the $GLOBALS array.

Example: Access the global variable $x inside a function.

<?php
$x = 50;
function displayValue() {
    global $x;
    echo $x;
}
displayValue();
/*
Output:
50
*/
?>

In PHP, if you refer to a global variable without using the $GLOBALS syntax, you will get nothing or an error.

Example: 

<?php
$x = 50;
function myFunction() {
    echo $x;
}
myFunction;
/*
The output will be empty.
*/
?>

Creating Global Variables

Variables created in the outermost scope are global variables, whether or not they are created using the $GLOBALS syntax.

<?php
$x = 200;
function displayGlobalVariable() {
   echo $GLOBALS["x"];
}
displayGlobalVariable();
/*
Output:
200
*/
?>

Variables created inside a function belong only to that function, but you can create global variables within a function using the $GLOBALS syntax, as shown below:

<?php
function updateGlobalVariable() {
    $GLOBALS["x"] = 200;
}
updateGlobalVariable();
echo "Using GLOBALS: " . $GLOBALS["x"] . "<br>";
echo "Directly: $x";
/*
Output:
Using GLOBALS: 200
Directly: 200
*/
?>

$_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

The example below shows how to use some of the elements in $_SERVER:

<?php
echo "Current script path: " . $_SERVER['PHP_SELF'] . "<br>";
echo "Server name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "Host name: " . $_SERVER['HTTP_HOST'] . "<br>";
echo "Referring page: " . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'No referrer') . "<br>";
echo "User agent: " . $_SERVER['HTTP_USER_AGENT'] . "<br>";
echo "Script name: " . $_SERVER['SCRIPT_NAME'] . "<br>";
/*
Output:
Current script path: /php/index.php
Server name: localhost
Host name: localhost
Referring page: No referrer
User agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
Script name: /php/index.php
*/
?>

Here is a list of key elements that can be found within $_SERVER.

  • $_SERVER['PHP_SELF']                                 Returns the filename of the currently executing script
  • $_SERVER['GATEWAY_INTERFACE']              Returns the version of the Common Gateway Interface (CGI) the server is using
  • $_SERVER['SERVER_ADDR']                           Returns the IP address of the host server
  • $_SERVER['SERVER_NAME']                           Returns the name of the host server (such as localhost)
  • $_SERVER['SERVER_SOFTWARE']                   Returns the server identification string (such as Apache/2.2.24)
  • $_SERVER['SERVER_PROTOCOL']                   Returns the name and revision of the information protocol (such as HTTP/1.1)
  • $_SERVER['REQUEST_METHOD']                     Returns the request method used to access the page (such as POST)
  • $_SERVER['REQUEST_TIME']                         Returns the timestamp of the start of the request (such as 1377687496)
  • $_SERVER['QUERY_STRING']                         Returns the query string if the page is accessed via a query string
  • $_SERVER['HTTP_ACCEPT']                           Returns the Accept header from the current request
  • $_SERVER['HTTP_ACCEPT_CHARSET']           Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
  • $_SERVER['HTTP_HOST']                               Returns the Host header from the current request
  • $_SERVER['HTTP_REFERER']                         Returns the complete URL of the current page (not reliable because not all user-agents support it)
  • $_SERVER['HTTPS']                                       Is the script queried through a secure HTTP protocol
  • $_SERVER['REMOTE_ADDR']                           Returns the IP address from where the user is viewing the current page
  • $_SERVER['REMOTE_HOST']                           Returns the Host name from where the user is viewing the current page
  • $_SERVER['REMOTE_PORT']                           Returns the port being used on the user's machine to communicate with the web server
  • $_SERVER['SCRIPT_FILENAME']                   Returns the absolute pathname of the currently executing script
  • $_SERVER['SERVER_ADMIN']                         Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) 
  • $_SERVER['SERVER_PORT']                           Returns the port on the server machine being used by the web server for communication (such as 80)
  • $_SERVER['SERVER_SIGNATURE']                  Returns the server version and virtual host name which are added to server-generated pages
  • $_SERVER['PATH_TRANSLATED']                    Returns the file system based path to the current script
  • $_SERVER['SCRIPT_NAME']                            Returns the path of the current script
  • $_SERVER['SCRIPT_URI']                              Returns the URI of the current page

$_REQUEST

$_REQUEST is a PHP superglobal variable that contains submitted form data as well as all cookie data.

In other words, $_REQUEST is an array that includes data from $_GET, $_POST, and $_COOKIE variables.

You can access this data using the $_REQUEST keyword followed by the name of the form field or cookie.

Example:

<?php
$_REQUEST['fname'];
// Where fname is a form field or cookie name 
?>

Using $_REQUEST on POST Requests

POST requests are typically used for submitting data from an HTML form.

The PHP file where the POST request is sent is specified in the action attribute in the form HTML tag, as you can see below.

Example HTML form:

<form method="post" action="process_form.php">
  <label for="fname">Enter your name:</label>
  <input type="text" id="fname" name="fname" placeholder="Your full name" required>
  <br><br>
  <input type="submit" value="Submit">
</form>

In the above example, when a user clicks the submit button, the form data is sent to the PHP file named process_form.php. The $_REQUEST variable can be used to retrieve the values of the input fields, as shown below.

<?php
$name = $_REQUEST['fname'];
echo $name;
?>

Using $_REQUEST on GET Requests

GET requests can be used for form submissions, by setting the method attribute of the HTML <form> element to GET.

GET requests can also retrieve data from a query string, which is information appended to a URL.

Example

<a href="file.php?title=PHP&web=webmastermaze.com">Web Link</a>

Where title and web are parameter names, and  PHP and webmastermaze.com are parameter values. Parameter name value pairs are separated by the ampersand(&) character.

In the above example, when a user clicks the link, the query string data is sent to the PHP file named file.php, where the code is executed.

Example file.php:

<?php
$subject = $_REQUEST['title'];
$web = $_REQUEST['web'];
echo "Study " . $title . " at " . $web;
/*
Output:
Study web at webmastermaze.com
*/
?>

$_POST

$_POST contains an array of variables received through the HTTP POST method.

For example, an HTML form submits data via the HTTP POST method if the form's method attribute is set to POST, as shown below.

<form method="POST" action="process_form.php">
    <label for="fname">Enter your name:</label>
    <input type="text" id="fname" name="fname" placeholder="Your full name" required>
    <br><br>
    <input type="submit" value="Submit">
</form>

In the above example, when a user clicks the submit button, the form data is sent to the PHP file named process_form.php.

In that PHP file, you can use the $_POST variable to retrieve the values of the input fields, as shown below.

<?php
$name = $_POST['fname'];
echo $name;
?>

$_GET

$_GET contains an array of variables received through the HTTP GET method.

<form method= "GET" action="process_form.php">
<label for="fname">Enter your name:</label>
<input type="text" id="fname" name="fname" placeholder="Your full name" required> <br><br>
<input type="submit" value="Submit">
</form>

In the PHP file, you can use the $_GET variable to retrieve the values from the query string, as shown below.

<?php
$name = $_GET['fname'];
echo $name;
?>

$_COOKIE

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Cookie values are stored in the $_COOKIE variable.

A cookie is created with the setcookie() function.

Example:

<?php
$cookie_name = "user";
$cookie_value = "James Bond";
setcookie($cookie_name, $cookie_value);
?>

You can retrieve the cookie value by using the $_COOKIE variable, as shown below. 

 <?php
if (isset($_COOKIE[$cookie_name])) { 
   echo "Name is: " . $_COOKIE[$cookie_name];
}
/*
Output:
Name is: James Bond
*/
?>

$_FILES

In PHP, $_FILES is a superglobal array that holds information about files uploaded via an HTML form using the POST method with the enctype="multipart/form-data" attribute.

Example:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="file" name="testfile">
   <input type="submit" value="Upload">
</form>

In the above example, when a user clicks the submit button, the form data is sent to the PHP file named upload.php.

In that PHP file, for example, if you want to check if the user submitted a file, you can use the below code (saving files on the server will be discussed in our later tutorials).

<?php
$file = $_FILES['testfile'] ?? null;
if ($file && $file['error'] === 0) {
  echo "File has been submitted successfully;
} else {
  echo "No file submitted.";
}
?>

$_SESSION

$_SESSION is a superglobal array used to store session variables in PHP. These variables can be used to store and maintain user settings and information across different pages during a user's session.

Example:

<?php
// Start the session
session_start();

// Set session variables
$_SESSION["favcolor"] = "blue";
$_SESSION["favanimal"] = "deer";

// Retrieve session variables
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";

/*
Output:
Favorite color is blue.
Favorite animal is deer.
*/
?>

Note: session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page by using session_start().

Questions & Answers