$_SERVER is an array filled by the web server. It tells you about the current request and the environment.
Keys you will use often
| Key | Contains |
|---|---|
REQUEST_METHOD | GET, POST and so on |
REQUEST_URI | The path and query string asked for, such as /blog?page=2 |
QUERY_STRING | The part after the ? |
SCRIPT_NAME | The path of the running script |
HTTPS | on when the page was loaded over HTTPS (may be missing) |
SERVER_NAME | The server’s name from its configuration |
HTTP_HOST | The host the visitor asked for (sent by the client) |
HTTP_USER_AGENT | The browser’s identifier (sent by the client) |
REMOTE_ADDR | The IP address of the connection |
REQUEST_TIME | When the request started (a Unix timestamp) |
DOCUMENT_ROOT | The web folder on disk |
<?php
echo $_SERVER["REQUEST_METHOD"]; // POST
echo $_SERVER["REQUEST_URI"]; // /contact.php?ref=home
Branching on the method
<?php
$_SERVER["REQUEST_METHOD"] = "POST";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
echo "Handle the form";
} else {
echo "Show the form";
}
Handle the form
Keys starting with HTTP_ come from the visitor
Anything starting with HTTP_ is a request header. The visitor controls these completely. That includes HTTP_HOST, HTTP_USER_AGENT, HTTP_REFERER and HTTP_X_FORWARDED_FOR.
- Do not use them for security decisions.
- Do not trust
HTTP_HOSTto build links in emails. An attacker can send a fake host (called host header injection). Put your real domain in your configuration. - Escape them before printing (
htmlspecialchars()).
The visitor’s IP address
REMOTE_ADDR is the address of whoever connected to the server. Behind a proxy or CDN, that is the proxy’s address, and the visitor’s real address is in a header such as X-Forwarded-For, which can be faked. Only trust that header if the request really came from your own proxy.
Detect HTTPS
<?php
function isHttps(): bool
{
return !empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off";
}
$_SERVER["HTTPS"] = "on";
var_dump(isHttps());
bool(true)
On the command line
In the CLI, $_SERVER["argv"] and $_SERVER["argc"] hold the command line arguments, and most web keys do not exist.
Not every key always exists
$_SERVER differently. Read with ?? ($_SERVER["HTTPS"] ?? "off"), or you will get warnings.