HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP $_SERVER Superglobal

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.


1. Common $_SERVER Keys

Here are the most frequently used elements inside the $_SERVER array:

Key Description
PHP_SELFReturns the filename of the currently executing script.
SERVER_NAMEReturns the name of the host server (e.g., localhost).
HTTP_HOSTReturns the Host header from the current request.
HTTP_USER_AGENTReturns the browser info of the user.
SCRIPT_NAMEReturns the path of the current script.
REMOTE_ADDRReturns the IP address of the user.

2. Practical Examples

Getting the Current Script URL

<?php
    echo $_SERVER['PHP_SELF'];
?>

Detecting User Browser

<?php
    echo $_SERVER['HTTP_USER_AGENT'];
?>

3. Security Warning: XSS

PHP_SELF can be used by hackers to inject code if you use it directly in a form's action attribute without sanitizing it.

Dangerous: <form action="<?php echo $_SERVER['PHP_SELF']; ?>">
Safe: <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Always Encoded: Just because the server provides this data doesn't mean it's safe to print. Always wrap server-provided strings in htmlspecialchars() before rendering.
Pro Tip: Use $_SERVER['REQUEST_METHOD'] to check if a form was submitted via POST or GET (e.g., if ($_SERVER["REQUEST_METHOD"] == "POST")).

Key Takeaways

  • $_SERVER provides environmental and request data.
  • PHP_SELF is often used for self-submitting forms.
  • REMOTE_ADDR helps identified user IP addresses.
  • Always sanitize $_SERVER data before echoing to prevent XSS attacks.