The $_SERVER superglobal is holds information about headers, paths, and script locations. It is an associative array that is automatically populated by the web server.
Here are the most frequently used elements inside the $_SERVER array:
| Key | Description |
|---|---|
PHP_SELF | Returns the filename of the currently executing script. |
SERVER_NAME | Returns the name of the host server (e.g., localhost). |
HTTP_HOST | Returns the Host header from the current request. |
HTTP_USER_AGENT | Returns the browser info of the user. |
SCRIPT_NAME | Returns the path of the current script. |
REMOTE_ADDR | Returns the IP address of the user. |
<?php
echo $_SERVER['PHP_SELF'];
?>
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
PHP_SELF can be used by hackers to inject code if you use it directly in a form's action attribute without sanitizing it.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"><form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
htmlspecialchars() before rendering.
$_SERVER['REQUEST_METHOD'] to check if a form was submitted via POST or GET (e.g., if ($_SERVER["REQUEST_METHOD"] == "POST")).
$_SERVER provides environmental and request data.PHP_SELF is often used for self-submitting forms.REMOTE_ADDR helps identified user IP addresses.$_SERVER data before echoing to prevent XSS attacks.