Superglobals

All variables that come into PHP arrive inside one of several special arrays known collectively as the superglobals. They're called superglobal because they are available everywhere in your script, even inside objects. These arrays were not available in PHP before v4.1, so ancient scripts use alternatives. The new versions are superior, though, so it is strongly recommended that all new scripts use the superglobals. Superglobals can be used like any other arrays in PHP, which means you can iterate through them, etc.

There are nine superglobals available for use, categorised by type of variable. These are:

Name

Functionality

$GLOBALS

Contains all global variables in your script, including other superglobals. This is not generally recommended for use, unless you are, for some reason, not sure where a variable will be stored. $GLOBALS has been available since PHP 3, and its operation has not changed.

$_GET

Contains all variables sent via a HTTP GET request. That is, sent by way of the URL.

$_POST

Contains all variables sent via a HTTP POST request.

$_FILES

Contains all variables sent via a HTTP POST file upload.

$_COOKIE

Contains all variables sent via HTTP cookies.

$_REQUEST

Contains all variables sent via HTTP GET, HTTP POST, and HTTP cookies. This is basically the equivalent of combining $_GET, $_POST, and $_COOKIE, and is less dangerous than using $GLOBALS. However, as it does contain all variables from untrusted sources (that is, your visitors), you should still try to steer clear unless you have very good reason to use it.

$_SESSION

Contains all variables stored in a user's session.

$_SERVER

Contains all variables set by the web server you are using, or other sources that directly relate to the execution of your script.

$_ENV

Contains all environment variables set by your system or shell for the script.

There are two superglobal arrays that I would discourage use of as much as possible, and these are $GLOBALS and $_REQUEST. Both of these two arrays are combinations of the other arrays, and therefore mingle together untrusted user data. When you use $_COOKIE['somevar'], you know that the value has come from a cookie on the user's machine, and not from someone editing the URL to your site. When using $_REQUEST['somevar'], however, you no longer have that guarantee, and you are left trusting the user to some extent.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Pre-set variables >>

Previous chapter: Variable variables

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.