How to Retrieve Server Information in PHP using $_SERVER

This article explains how to use PHP’s superglobal $_SERVER array to retrieve essential server and execution environment information. You will learn about the most commonly used keys in this array, how to access them securely, and practical examples of displaying server details like IP addresses, headers, and script paths.

What is the PHP $_SERVER Array?

The $_SERVER variable is a built-in PHP superglobal array that contains information created by the web server. It includes data about headers, paths, script locations, and network environments. Because it is a superglobal, it is accessible from any scope in your PHP script without needing to declare it as global.

Commonly Used $_SERVER Keys

While the $_SERVER array contains dozens of elements, several keys are used frequently to gather server and request information:

Code Example: Retrieving and Displaying Server Data

To retrieve these values, you reference the specific key inside the $_SERVER array. The following PHP script demonstrates how to fetch and display basic server and client information:

<?php
// Retrieve server information
$serverName = $_SERVER['SERVER_NAME'];
$serverSoftware = $_SERVER['SERVER_SOFTWARE'];
$serverIp = $_SERVER['SERVER_ADDR'] ?? 'Not defined';

// Retrieve request and client information
$requestMethod = $_SERVER['REQUEST_METHOD'];
$clientIp = $_SERVER['REMOTE_ADDR'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];

// Display the retrieved information
echo "<h3>Server Information</h3>";
echo "Server Name: " . htmlspecialchars($serverName) . "<br>";
echo "Server Software: " . htmlspecialchars($serverSoftware) . "<br>";
echo "Server IP: " . htmlspecialchars($serverIp) . "<br>";

echo "<h3>Request & Client Information</h3>";
echo "Request Method: " . htmlspecialchars($requestMethod) . "<br>";
echo "Client IP Address: " . htmlspecialchars($clientIp) . "<br>";
echo "Client User Agent: " . htmlspecialchars($userAgent) . "<br>";
?>

Security Considerations

When using the $_SERVER array, keep in mind that some values are provided by the client’s browser (such as HTTP_USER_AGENT and headers). Because these values can be manipulated by malicious users, always sanitize or escape them using functions like htmlspecialchars() before outputting them to the browser to prevent Cross-Site Scripting (XSS) attacks.