In this post, I’ll give you a cheatsheet quick reference to all the PHP superglobal variables available in PHP.
What Is a Superglobal Variable?
Let’s have a look at the definition of superglobal variables.
Superglobals are built-in variables that are always available in all scopes.
Whether you are a seasoned PHP developer or a novice in PHP development, you will have worked with these superglobal variables in one way or another. There are several predefined variables in PHP that are considered as superglobals, which means that you don’t need to use the global
keyword to access them. The superglobal variables are available in all scopes of a script.
Let’s have a quick look at the superglobal variables in PHP:
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
The aim of this article is to go through all the superglobal variables in PHP and explain each one briefly.
PHP Superglobal Quick Reference
$GLOBALS
The $GLOBALS
superglobal variable is used to access all the global variables in PHP. Basically, it’s an associative array which holds all variables that are defined in the global scope.
Let’s have a look at the following example to understand how it works.
<?php // variable defined in the global scope $website_name = 'tutsplus.com'; function displayWebsiteName() { // PHP Notice: Undefined variable: website_name echo 'Website: ' . $website_name; // outputs “Website: tutsplus.com” echo $GLOBALS['website_name']; } displayWebsiteName();
Firstly, we’ve defined the $website_name
variable in the global scope.
Now, when we try to access the $website_name
variable in the displayWebsiteName
function, it will try to find the $website_name
variable in the local scope. And since haven’t defined it in the displayWebsiteName
function, you’ll get a PHP notice complaining that you’re trying to access an undefined variable.
Next, when we try to access it with the $GLOBALS
superglobal, it works since the $GLOBALS
variable holds references to all global variables.
$_SERVER
The $_SERVER
superglobal variable holds the web server and execution environment information. Specifically, it’s initialized by a web server with HTTP headers, paths, and script locations.
Let’s have a look at the output of the print_r($_SERVER)
command.
Array ( [USER] => ubuntu [HOME] => /var/www [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 [HTTP_COOKIE] => _ga=GA1.1.19480044.1597729890; _hjid=41b3ce18-a24c-41d4-ac7f-dc5d9066120d; _ga_17Y2VJYG6X=GS1.1.1606729885.14.1.1606730391.0; __gads=ID=4fad16ec33ad9598:T=1606730074:S=ALNI_MaYqS1Ftx7eMR2naLutOqRPT1LytQ [HTTP_CONNECTION] => keep-alive [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 [HTTP_USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 [HTTP_HOST] => localhost [REDIRECT_STATUS] => 200 [SERVER_NAME] => localhost [SERVER_PORT] => 80 [SERVER_ADDR] => 127.0.0.1 [REMOTE_PORT] => 39482 [REMOTE_ADDR] => 127.0.0.1 [SERVER_SOFTWARE] => nginx/1.14.0 [GATEWAY_INTERFACE] => CGI/1.1 [REQUEST_SCHEME] => http [SERVER_PROTOCOL] => HTTP/1.1 [DOCUMENT_ROOT] => /web/demoproject [DOCUMENT_URI] => /server.php [REQUEST_URI] => /server.php [SCRIPT_NAME] => /server.php [CONTENT_LENGTH] => [CONTENT_TYPE] => [REQUEST_METHOD] => GET [QUERY_STRING] => [SCRIPT_FILENAME] => /web/demoproject/server.php [FCGI_ROLE] => RESPONDER [PHP_SELF] => /server.php [REQUEST_TIME_FLOAT] => 1613665334.6422 [REQUEST_TIME] => 1613665334 )
Mostly, this contains server-specific information like the server name, server port, script name, document root, and so on. Apart from that, it may also contain information about the client environment like user agent, remote IP address, cookies, and more.
The important thing is that there’s no guarantee that every web server will initialize all this information. Also, if you’re running a script from the command line, none of the SERVER_*
variables are initialized, as they are server-specific.
$_GET
When a user submits a form with the GET method, the form data which is sent to a server is available in the $_GET
variable. The $_GET
superglobal variable contains an array of variables that are passed to the script via a query string. Basically, anything which is passed as a part of the URL query string will be available in the $_GET
superglobal variable.
Let’s have a look at the following snippet.
<form action = "/search.php" method = "GET"> Search Keyword: <input type = "text" name = "keyword" /> <input type = "submit" value=”Search”/> </form>
In the above example, when a user submits the search form, the value of the keyword field will be sent to a server via a query string.
/search.php?keyword=PHP
On the server side, you can access it like this:
<?php If (isset($_GET['keyword'])) { $search_keyword = filter_var($_GET['keyword'], FILTER_SANITIZE_STRING); } ?>
You must sanitize the user input before it’s processed or displayed back to the browser, and that’s why we’ve used the filter_var
function to sanitize the value of the $_GET[‘keyword’]
variable.
$_POST
Where the $_GET
superglobal variable is used to collect form data which is submitted with the GET method, the $_POST
superglobal variable is used to get the form data for the POST method. The POST form data won’t be displayed in the URL; instead, it’s available as a part of the request body.
Let’s have a look at the following snippet.
<form action="/login.php" method="POST"> Username: <input type="text" name="username" /> Password: <input type="password" name="password" /> <input type="submit" value="Login"/> </form>
In the above example, when a user submits the search form, you can access the field values like this on the server side.
<?php If (isset($_POST['username']) && isset($_POST['password'])) { $username = $_POST['username']; $password = $_POST['password']; } ?>
When you work with the $_POST
data, you must ensure that you’re taking enough measures to sanitize the incoming data, otherwise it could lead to potential attacks on your site.
$_FILES
When a user submits a form which supports file uploads, the $_FILES
superglobal variable will be populated with the information of the files that are uploaded. It’s a two-dimensional array which holds the following attributes of uploaded files:
- name: name of the file
- type: type of the file
- size: size of the file
- tmp_name: server path of the uploaded file
- error: error if file upload has failed
Let’s have a look at the following example to see how file uploads work in PHP.
<!DOCTYPE html> <html> <body> <div> <form action="upload.php" method="POST" enctype="multipart/form-data"> Upload File:<input type="file" name="document"> <input type="submit" value="Upload" name="Submit"> </form> </div> </body> </html>
In the above example, we’ve set the enctype
attribute to multipart/form-data
, and thus it enables file uploads. When a user submits a file, you can use the $_FILES
superglobal variable to access the uploaded file information, as shown in the following snippet.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_FILES["document"]) && $_FILES["document"]["error"] === UPLOAD_ERR_OK) { $fileName = $_FILES["document"]["name"]; $fileType = $_FILES["document"]["type"]; $fileSize = $_FILES["document"]["size"]; $fileTmpName = $_FILES["document"]["tmp_name"]; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(end($fileNameCmps)); // sanitize file-name $newFileName = md5(time() . $fileName) . '.' . $fileExtension; // check if file has one of the following extensions $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc'); if (in_array($fileExtension, $allowedfileExtensions)) { $uploadFileDir = './uploaded_files/'; $dest_path = $uploadFileDir . $newFileName; if(move_uploaded_file($fileTmpPath, $dest_path)) { $message ='File is successfully uploaded.'; } else { $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; } } else { $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions); } echo $message; } else { echo 'There was some error uploading the file:' . $_FILES["document"]["error"]; } } ?>
The important thing is that the $_FILES["document"]["tmp_name"]
variable contains the path of the uploaded file, which you could use to move the uploaded file to the desired location. If there’s an error, the $_FILES["document"]["error"]
variable will be populated with it.
$_COOKIE
As the name suggests, the $_COOKIE
superglobal variable is used to read cookies that are available to the current script. Basically, it allows you to access cookies that are already set by the setcookie
function in PHP. The $_COOKIE
variable is an associate array which holds all cookie variables that are sent via HTTP cookies.
Let’s assume that you’ve already created the lastVisitedSection
cookie with the following snippet.
<?php setcookie('lastVisitedSection', 'codeTutsPlus', time() + 3600, "/"); ?>
Now, you can access the lastVisitedSection
cookie, as shown in the following snippet.
<?php if(isset($_COOKIE['lastVisitedSection'])) { echo 'Last visited section:' . htmlspecialchars($_COOKIE['lastVisitedSection']); } else { echo 'We encourage you to explore different sections of tutsplus.com!'; } ?>
So that’s how you can access cookies in your script.
$_SESSION
If you’ve already worked with sessions in PHP, you’ll be aware of the $_SESSION
superglobal variable. A session variable allows you to share information across the different pages of a single site or app—thus it helps maintain state. The $_SESSION
variable holds an associative array of session variables that are available to the current script.
Let’s have a look at the following example, which demonstrates how to set and get a session variable.
<?php session_start(); // set a session variable $_SESSION['loggedInUserName'] = 'John'; // get a session variable later in the script or in subsequent requests If (isset($_SESSION['loggedInUserName'])) { echo 'Hello, '. $_SESSION['loggedInUserName']; } else { echo 'Login Now!'; } ?>
The important thing is that the session_start
function must be called at the beginning of the script to start a session and initialize the $_SESSION
variable.
$_REQUEST
The $_REQUEST
superglobal variable is an associative array which holds HTTP request variables. Basically, it’s a combination of the$_GET
, $_POST
, and $_COOKIE
superglobal variables. And thus, it’s convenient to use the $_REQUEST
variable, specifically if you don’t want to use the aforementioned superglobal variables.
The presence and order of variables in this array depend on the values of the request_order
and variables_order
configuration directives in the php.ini file. You should be always careful when you use the $_REQUEST
variable, and in fact, it’s recommended that you go with $_GET
, $_POST
, and $_COOKIE
instead of using this superglobal variable.
$_ENV
The $_ENV
superglobal variable is an associative array of variables that are passed to the script by the environment method. It’s useful when you want to set different values for different environments like local, staging, and production. In your application, you would have database credentials and configuration variables that are different for each environment, and thus, you could use the $_ENV
variable to access them in your script since they are initialized dynamically. There are different ways that you could use to set the environment variables.
In PHP, you can use the putenv
function to initialize it, as shown in the following snippet.
putenv('HOSTNAME=localhost');
On the other hand, if you want to set an environment variable in the Apache virtual host file, use:
SetEnv HOSTNAME localhost
You should always prefer the getenv
function to get the value of an environment variable.
$hostname = getenv('HOSTNAME');
You should always use the getenv
function to retrieve the value of an environment variable, since the $_ENV
variable might be empty if you haven’t enabled it via the variables_order
configuration directive in the php.ini file. The variables_order
configuration directive defines the order in which the EGPCS (Environment, Get, Post, Cookie, and Server) variables will be initialized.
Conclusion
In this article, we’ve gone through all the PHP superglobal variables available in PHP. For every variable, I provided a short but meaningful example which should help you to understand its purpose. And I hope you can use this article as a quick reference or a cheatsheet in your day-to-day PHP development.