start learning
Image 1
501017788740112

$_SERVER Superglobal in PHP

In PHP, $_SERVER is a superglobal variable that contains an array of information about the server and the current request. It provides details about the web server, the script being executed, and information related to the client's request. $_SERVER is an essential tool for accessing environmental data, handling server-related tasks, and gathering information about the current HTTP request.


Example with Clarification :

Here's an example that demonstrates how to use the $_SERVER superglobal to access various server-related information.

<!DOCTYPE html>
<html>
<head>
    <title>PHP GET Example</title>
</head>
<body>
   <h2>Server Information</h2>
    <ul>
        <li>Server Name: <?php echo $_SERVER['SERVER_NAME']; ?></li>
        <li>Server Address: <?php echo $_SERVER['SERVER_ADDR']; ?></li>
        <li>Server Port: <?php echo $_SERVER['SERVER_PORT']; ?></li>
        <li>Document Root: <?php echo $_SERVER['DOCUMENT_ROOT']; ?></li>
    </ul>
    <h2>Request Information</h2>
    <ul>
        <li>Client IP Address: <?php echo $_SERVER['REMOTE_ADDR']; ?></li>
        <li>Request Method: <?php echo $_SERVER['REQUEST_METHOD']; ?></li>
        <li>Request URI: <?php echo $_SERVER['REQUEST_URI']; ?></li>
        <li>User Agent: <?php echo $_SERVER['HTTP_USER_AGENT']; ?></li>
    </ul>
</body>
</html>

  1. In this example, we create a simple HTML page that displays server and request information using the $_SERVER superglobal.
  2. We access the server-related information, such as the server name, server address, server port, and document root, using $_SERVER['SERVER_NAME'], $_SERVER['SERVER_ADDR'], $_SERVER['SERVER_PORT'], and $_SERVER['DOCUMENT_ROOT'], respectively.
  3. We also access request-related information, such as the client's IP address, request method, request URI, and user agent, using $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], and $_SERVER['HTTP_USER_AGENT'].
  4. These values are displayed within HTML list elements, making it easy to read and understand the server and request details.

The $_SERVER superglobal is a valuable resource for retrieving essential information about the server environment and the current HTTP request. It allows you to access various server variables and data, enabling you to build more dynamic and responsive web applications that can adapt to different server configurations and client requests.


×