The $_SERVER Array
$_SERVER holds information about headers, paths and the request.
$_SERVER is an array containing information created by the web server, such as:
$_SERVER['REQUEST_METHOD']— GET or POST.$_SERVER['HTTP_HOST']— the host name.$_SERVER['REQUEST_URI']— the requested path.$_SERVER['PHP_SELF']— the current script name.
These keys are filled by a real web request, so the values differ on the command line.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Log the client's IP address from $_SERVER['REMOTE_ADDR'] for audit trails on sensitive actions.
- Read $_SERVER['HTTP_USER_AGENT'] to detect bots and serve a reduced-payload response.
- Construct the canonical URL of the current page using $_SERVER['HTTP_HOST'] and REQUEST_URI for SEO.
More examples
Getting the current URL
Combining HTTPS, HTTP_HOST, and REQUEST_URI reconstructs the full URL of the current request.
<?php
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];
$current = "$scheme://$host$uri";
echo $current;Logging client IP
REMOTE_ADDR is the direct connection IP; HTTP_X_FORWARDED_FOR is checked first for reverse-proxy setups.
<?php
function getClientIp(): string {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
}
return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}
echo getClientIp();Detecting the script path
$_SERVER exposes the filesystem path, web root, HTTP method, and user agent — common inputs for routing and logging.
<?php
echo 'Script: ' . $_SERVER['SCRIPT_FILENAME'] . "\n";
echo 'Root: ' . $_SERVER['DOCUMENT_ROOT'] . "\n";
echo 'Method: ' . $_SERVER['REQUEST_METHOD'] . "\n";
echo 'Agent: ' . ($_SERVER['HTTP_USER_AGENT'] ?? 'none');
Discussion