W3docs

$_SERVER

PHP is a popular server-side scripting language used for web development. One of its unique features is the use of superglobals, which are special variables

Understanding PHP Superglobals and the $_SERVER Variable

PHP is a popular server-side scripting language used for web development. One of its features is the set of superglobals — built-in variables that are always available in every scope, so you never have to declare them with the global keyword. This article focuses on the $_SERVER superglobal: what it holds, the keys you'll use most, and how to read it safely.

For an overview of all the superglobals ($_GET, $_POST, $_SESSION, $_COOKIE, and more), see PHP Superglobals.

What is the $_SERVER Variable?

$_SERVER is an associative array that the web server fills in for every request. It holds information about the server, the current script, and the incoming HTTP request — headers, paths, the request method, the visitor's IP address, and selected system environment variables.

Because it is an array, you read individual pieces of information by key, for example $_SERVER['REQUEST_METHOD'].

Commonly used keys

KeyWhat it returns
$_SERVER['REQUEST_METHOD']The HTTP method of the request (GET, POST, PUT, …).
$_SERVER['REQUEST_URI']The path and query string of the requested URL, e.g. /products?id=5.
$_SERVER['QUERY_STRING']Only the query-string portion of the URL, e.g. id=5.
$_SERVER['HTTP_HOST']The host (and port) from the request's Host header.
$_SERVER['SERVER_NAME']The host name as configured on the server itself.
$_SERVER['HTTPS']Non-empty when the request was made over HTTPS.
$_SERVER['REMOTE_ADDR']The IP address the request appears to come from.
$_SERVER['HTTP_USER_AGENT']The client's User-Agent header (browser/bot identity).
$_SERVER['HTTP_REFERER']The URL of the page that linked to the current script, if any.
$_SERVER['SCRIPT_FILENAME']Absolute filesystem path of the executing script.
$_SERVER['DOCUMENT_ROOT']Document root directory configured for the site.
$_SERVER['PHP_SELF']Path of the current script relative to the document root.
$_SERVER['SERVER_PROTOCOL']Protocol of the request, e.g. HTTP/1.1.

Note: Which keys are present depends on the web server (Apache, Nginx + PHP-FPM, the built-in CLI server, …). On the command line many request-related keys are missing entirely. Always read with care — see the safety section below.

Inspecting $_SERVER

When you're unsure what a given environment provides, dump the whole array:

<?php
echo '<pre>';
print_r($_SERVER);
echo '</pre>';

This prints every key/value pair the server made available for the current request, which is the quickest way to discover what you can rely on.

Branching on the request method

A very common use of $_SERVER is deciding what to do based on how the page was requested. A form page, for instance, shows the form on a GET request and processes the submitted data on a POST request:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle the submitted form data (validate, save, …)
    echo 'Processing your submission';
} else {
    // First visit — show the empty form
    echo 'Showing the form';
}

This pattern is the backbone of form handling in PHP. See PHP Form Handling and PHP Form Validation for the full workflow.

Building a redirect URL

The header() function sends a raw HTTP header — including the Location header used for redirects. $_SERVER is handy for building the destination dynamically, for example forcing HTTPS for the current request:

<?php
// Redirect to the HTTPS version of the same URL when the request is plain HTTP
if (empty($_SERVER['HTTPS'])) {
    $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('Location: ' . $url, true, 301);
    exit;
}

header() must be called before any output (HTML, echo, or even a blank line) is sent to the browser. The exit statement halts the script so no further content is produced after the redirect header.

Using $_SERVER for Error Handling

Another use of the $_SERVER variable is for error handling. For example, you can use the following code to display a custom error page for 404 errors:

PHP 404 error handling with $_SERVER

<?php
// Log the error URI using $_SERVER
error_log('404 Error: ' . $_SERVER['REQUEST_URI']);
http_response_code(404);
include '404.html';
?>

In this example, $_SERVER['REQUEST_URI'] is used to capture the requested path for logging purposes. Instead of redirecting, the script sets the correct HTTP status code and includes a custom template, which is the standard practice for handling errors.

Security: don't trust client-controlled values

Some $_SERVER keys come from the request and are fully controlled by the client, so they can be forged. Treat them as untrusted input:

  • HTTP_HOST, HTTP_REFERER, HTTP_USER_AGENT and any other HTTP_* key are just request headers — a malicious client can send anything. Never echo them into HTML without escaping (use htmlspecialchars()), and validate HTTP_HOST against an allow-list before using it in a redirect.
  • PHP_SELF can carry injected path data and is a classic source of cross-site scripting (XSS) when printed in a form's action attribute. Escape it.
  • REMOTE_ADDR is the connecting address; behind a proxy or load balancer the real client IP may be in a different header. Don't rely on REMOTE_ADDR alone for security decisions.

A safe way to check for a missing key without a warning is the null-coalescing operator:

<?php
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
echo $method;

This avoids an "undefined array key" warning when the key isn't set (for example when running under the CLI).

Conclusion

The $_SERVER superglobal gives PHP scripts access to request and environment details — the HTTP method, the requested URL, host, paths, and the visitor's IP. It powers everyday tasks such as method-based form handling, redirects, and error logging. Just remember that header-derived keys are client-controlled: validate and escape them before use.

To go further, explore the related superglobals: $_GET, $_POST, and $_REQUEST.

Note: In modern PHP, the closing ?> tag is optional and often omitted to prevent accidental whitespace output.

Practice

Practice
What information can PHP $_SERVER superglobal variable provide?
What information can PHP $_SERVER superglobal variable provide?
Was this page helpful?