$_SERVER in PHP

The $_SERVER superglobal is an associative array that contains information about headers, paths, and script locations. It is populated by the web server and provides valuable information about the server environment and the current request.

Common $_SERVER Variables

  • $_SERVER['SERVER_NAME']: The name of the server host.
  • $_SERVER['REQUEST_METHOD']: The request method used to access the page (GET, POST, etc.).
  • $_SERVER['SCRIPT_NAME']: The path of the currently executing script.
  • $_SERVER['REMOTE_ADDR']: The IP address of the client making the request.

Example of Using $_SERVER

<?php
// Display the server name
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "\n";
// Display the request method
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "\n";
// Display the script name
echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "\n";
// Display the client's IP address
echo "Client IP: " . $_SERVER['REMOTE_ADDR'] . "\n";
?>

Output:

Server Name: localhost
Request Method: GET
Script Name: /example.php
Client IP: 127.0.0.1

Explanation: This example demonstrates how to access various server-related information using the $_SERVER superglobal.