← Back to Chapters

PHP $_SERVER Variable

? PHP $_SERVER Variable

? Quick Overview

The $_SERVER superglobal in PHP is an associative array containing information about headers, paths, and script locations. It provides details about the server environment, current request, and client data.

? Key Concepts

  • $_SERVER is always available in PHP scripts
  • It contains server, request, and execution environment data
  • Values depend on the server configuration and request type

? Syntax / Theory

$_SERVER stores predefined indices that expose server and request-related metadata. These values are populated by the web server and PHP runtime.

? Example 1: SERVER_NAME

? View Code Example
// Display the server host name
<?php
echo "Server name: " . $_SERVER['SERVER_NAME'];
?>

? Example 2: REQUEST_URI

? View Code Example
// Show the current request URI
<?php
echo "Current URI: " . $_SERVER['REQUEST_URI'];
?>

? Example 3: REMOTE_ADDR

? View Code Example
// Fetch the client IP address
<?php
echo "Client IP address: " . $_SERVER['REMOTE_ADDR'];
?>

? Example 4: HTTP_USER_AGENT

? View Code Example
// Output browser and OS information
<?php
echo "User agent: " . $_SERVER['HTTP_USER_AGENT'];
?>

? Live Output / Explanation

These examples output dynamic server values such as hostname, URL path, client IP address, and browser information depending on the request environment.

? Interactive Diagram

Browser Web Server PHP $_SERVER

? Use Cases

  • Detecting the current page URL
  • Logging visitor IP addresses
  • Browser and device detection
  • Dynamic server-based routing

✅ Tips & Best Practices

  • Use $_SERVER values dynamically instead of hardcoding URLs
  • Sanitize output when displaying server values
  • Be cautious when using IP or user-agent data for security

? Try It Yourself

  • Display $_SERVER['SCRIPT_NAME']
  • Print all $_SERVER values using a loop
  • Extract browser name from HTTP_USER_AGENT