Skip to content

PHP Superglobals

Superglobals are built-in variables in PHP that are always available in all scopes. You can access them from any function, class, or file without needing to declare them as global or pass them as arguments.

PHP provides several predefined superglobal variables:

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

This chapter explores some of the most commonly used superglobals. Others, like $_SESSION, $_COOKIE, and $_FILES, are typically covered in more detail in chapters related to sessions, cookies, and file uploads, respectively.

$GLOBALS is an associative array containing references to all variables currently defined in the global scope of the script. The keys of this array are the names of the global variables.

This allows you to access global variables from within local scopes like functions or methods.

Example:

<?php
$x = 75;
$y = 25;
function addition() {
// Access global variables $x and $y using $GLOBALS
// and store the result in a new global variable $z
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo "The sum is: " . $z; // Access the globally defined $z
?>
Output:

The sum is: 100

Caution: While $GLOBALS provides access to global variables, over-reliance on it can lead to less maintainable and harder-to-debug code. It couples functions tightly to the global state. Consider passing variables as function arguments or using dependency injection for better code structure.

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide all of these; servers may omit some, or provide others not listed here.

Example:

<?php
echo 'Script Filename: ' . htmlspecialchars($_SERVER['PHP_SELF']) . "<br>";
echo 'Server Name: ' . htmlspecialchars($_SERVER['SERVER_NAME']) . "<br>";
echo 'HTTP Host: ' . htmlspecialchars($_SERVER['HTTP_HOST']) . "<br>";
// HTTP_REFERER is not always reliable or present
echo 'HTTP Referer: ' . (isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : 'N/A') . "<br>";
echo 'User Agent: ' . htmlspecialchars($_SERVER['HTTP_USER_AGENT']) . "<br>";
echo 'Script Name: ' . htmlspecialchars($_SERVER['SCRIPT_NAME']) . "<br>";
echo 'Request Method: ' . htmlspecialchars($_SERVER['REQUEST_METHOD']) . "<br>";
echo 'Remote Address: ' . htmlspecialchars($_SERVER['REMOTE_ADDR']) . "<br>";
?>

Common $_SERVER Elements:

Element/CodeDescription
$_SERVER['PHP_SELF']The filename of the currently executing script, relative to the document root. Be cautious when echoing this directly into HTML (see Security Note below).
$_SERVER['GATEWAY_INTERFACE']The version of the Common Gateway Interface (CGI) the server is using.
$_SERVER['SERVER_ADDR']The IP address of the server under which the current script is executing.
$_SERVER['SERVER_NAME']The name of the server host under which the current script is executing. (e.g., ‘www.example.com’)
$_SERVER['SERVER_SOFTWARE']Server identification string (e.g., ‘Apache/2.4.41 (Ubuntu)‘)
$_SERVER['SERVER_PROTOCOL']Name and revision of the information protocol (e.g., ‘HTTP/1.1’).
$_SERVER['REQUEST_METHOD']Which request method was used to access the page (e.g., ‘GET’, ‘POST’, ‘PUT’).
$_SERVER['REQUEST_TIME_FLOAT']The timestamp of the start of the request, with microsecond precision (float).
$_SERVER['REQUEST_TIME']The timestamp of the start of the request (integer).
$_SERVER['QUERY_STRING']The query string, if any, via which the page was accessed.
$_SERVER['HTTP_HOST']Contents of the Host: header from the current request.
$_SERVER['HTTP_REFERER']The address of the page (if any) which referred the user agent to the current page. Not reliable, as it depends on the user agent.
$_SERVER['HTTP_USER_AGENT']Contents of the User-Agent: header from the current request.
$_SERVER['HTTPS']Set to a non-empty value if the script was queried through a secure HTTPS protocol.
$_SERVER['REMOTE_ADDR']The IP address from which the user is viewing the current page. Can be unreliable if behind a proxy.
$_SERVER['REMOTE_HOST']The Host name from which the user is viewing the current page. May require DNS lookup.
$_SERVER['REMOTE_PORT']The port being used on the user’s machine to communicate with the web server.
$_SERVER['SCRIPT_FILENAME']The absolute pathname of the currently executing script.
$_SERVER['SERVER_PORT']The port on the server machine being used by the web server for communication (e.g., ‘80’, ‘443’).
$_SERVER['SCRIPT_NAME']Contains the current script’s path. Useful for links pointing to the script itself.
$_SERVER['REQUEST_URI']The URI which was given in order to access this page (e.g., ‘/index.html’).

Security Note on $_SERVER['PHP_SELF']: Never echo $_SERVER['PHP_SELF'] directly into HTML attributes (like a form’s action) without escaping it using htmlspecialchars(). Failure to do so can lead to Cross-Site Scripting (XSS) vulnerabilities. See the Form Validation chapter for details.

$_REQUEST is an associative array that, by default, contains the contents of $_GET, $_POST, and $_COOKIE.

While convenient, using $_REQUEST can sometimes make it unclear where a piece of data originated (GET, POST, or COOKIE), which can have security implications. It’s generally recommended to use the more specific $_GET or $_POST arrays when you know how the data is being submitted (e.g., via a form method or URL parameters).

Example (demonstrating access, but prefer $_POST or $_GET):

form.html
<html>
<body>
<form method="post" action="process.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<a href="process.php?city=London">Send City via GET</a>
</body>
</html>
process.php
<?php
// Using $_REQUEST (less specific)
if (isset($_REQUEST['fname'])) {
$name = htmlspecialchars($_REQUEST['fname']); // Sanitize output
echo "Name submitted via POST (likely): " . $name . "<br>";
}
if (isset($_REQUEST['city'])) {
$city = htmlspecialchars($_REQUEST['city']); // Sanitize output
echo "City submitted via GET (likely): " . $city . "<br>";
}
// Preferred approach:
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['fname'])) {
$name_post = htmlspecialchars($_POST['fname']);
echo "Using POST explicitly: Name = " . $name_post . "<br>";
}
if (isset($_GET['city'])) {
$city_get = htmlspecialchars($_GET['city']);
echo "Using GET explicitly: City = " . $city_get . "<br>";
}
?>

$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

It is commonly used to collect data submitted from an HTML form with method="post".

Example:

<!-- post_form.php -->
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
Name: <input type="text" name="username">
<input type="submit" value="Submit Name">
</form>
<?php
// Check if the form was submitted using POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect value of input field, apply basic output escaping
// IMPORTANT: Real applications need robust validation & sanitization!
$name = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
if (empty($name)) {
echo "<p style='color:red;'>Name is empty!</p>";
} else {
echo "<p>Hello, " . $name . "!</p>";
}
}
?>
</body>
</html>

When the user clicks “Submit Name”, the form data is sent via POST to the same script (post_form.php). The PHP code block checks if the request method is POST and then accesses the submitted ‘username’ value using $_POST['username'].

$_GET is an associative array of variables passed to the current script via the URL parameters (query string).

It’s commonly used to retrieve data sent from an HTML form with method="get" or directly embedded in hyperlinks.

Example with a hyperlink:

page1.html
<html>
<body>
<a href="test_get.php?subject=PHP&topic=Superglobals">Test GET Request</a>
</body>
</html>

When a user clicks the link, the browser navigates to test_get.php, sending subject and topic as URL parameters. The test_get.php script can access these values using $_GET:

test_get.php
<?php
// Access values from the query string, apply basic output escaping
// IMPORTANT: Real applications need robust validation & sanitization!
$subject = isset($_GET['subject']) ? htmlspecialchars($_GET['subject']) : 'Default Subject';
$topic = isset($_GET['topic']) ? htmlspecialchars($_GET['topic']) : 'Default Topic';
echo "Studying " . $subject . " focusing on " . $topic . ".";
?>
Output:

Studying PHP focusing on Superglobals.

Important: Data from $_GET, $_POST, and $_REQUEST comes from the user and should never be trusted. Always validate and sanitize this data before using it in database queries, displaying it in HTML, or processing it further to prevent security vulnerabilities like XSS and SQL injection. The htmlspecialchars() function used in examples provides basic output escaping, but comprehensive validation is crucial.