29. The $_SERVER Superglobal
The $_SERVER superglobal is an array containing information created by the web server, headers, paths, and script locations. It is extremely useful for routing, logging, and security checks.
Key Elements of $_SERVER
| Key | Description | Example Value |
|---|---|---|
$_SERVER['PHP_SELF'] | Filename of the currently executing script. | /index.php |
$_SERVER['SERVER_NAME'] | Name of the host server. | localhost |
$_SERVER['REQUEST_METHOD'] | The HTTP method used to access the page. | GET, POST, PUT |
$_SERVER['REMOTE_ADDR'] | The IP address of the user viewing the current page. | 127.0.0.1 |
$_SERVER['HTTP_USER_AGENT'] | Browser and OS information of the client. | Mozilla/5.0... |
Practical Usage: Checking Request Method
As seen in the forms lesson, we often use REQUEST_METHOD to differentiate between a simple page load (GET) and a form submission (POST).
php
Practical Usage: Self-Submitting Forms (Security Note)
While we use <?php echo $_SERVER['PHP_SELF']; ?> to submit forms back to themselves, it is vulnerable to Cross-Site Scripting (XSS) if not properly sanitized. For production code, always use the built-in function htmlspecialchars() to sanitize the output, preventing attackers from injecting malicious code into the URL that gets echoed back.
html