PHP $_SERVER: Basics and Examples

PHP $_SERVER is a superglobal. It’s a predefined variable containing information about your server, client, and request environment.

As a superglobal, PHP $_SERVER can be accessed anywhere within your script. It’s useful for retrieving server and request-specific data quickly. It contains information like client IP address, server name, HTTP request method, and more.

In the next sections, you’ll see common keys in the $_SERVER array and how to use them in web application development.

Getting the User’s IP Address

A common usage of $_SERVER is to get the user’s IP address. This may be useful in logging visitor data, analyzing the flow of visitors to the website, or location-based services.

The client’s IP could be retrieved with the $_SERVER['REMOTE_ADDR'] variable. However, if users connect from behind a proxy, then $_SERVER['REMOTE_ADDR'] will not produce the correct IP address.

In such cases, depending on the server configuration, the real IP is hidden in other keys like $_SERVER['HTTP_X_FORWARDED_FOR'] or $_SERVER['HTTP_CLIENT_IP'].

Here is an example that shows you how to fetch an IP address:

$user_ip = $_SERVER['REMOTE_ADDR'];
echo "User IP Address: " . $user_ip;

In the next section, you will learn how to retrieve information about the user’s browser.

Detecting the User’s Browser and Operating System

It’s useful to know the user’s browser and operating system if you have special content for specific browsers or operating systems. It also helps troubleshoot compatibility issues.

The $_SERVER['HTTP_USER_AGENT'] variable contains information about the client’s browser, operating system, and device.

This is usually a single string but sometimes complex-looking and full of details you can parse to customize for the user. For instance, you might show different content to users with older browsers.

Here is an example of how to get browser details:

$user_browser = $_SERVER['HTTP_USER_AGENT'];
echo "User Browser Info: " . $user_browser;

Now that we have covered user IPs and browser detection, let’s move on to the following section to see how to get server-side information.

Accessing Server Information with $_SERVER

PHP $_SERVER also provides a lot of useful information about the server itself. Variables such as $_SERVER['SERVER_NAME'] and $_SERVER['SERVER_SOFTWARE'] provide a way to identify the server and its software.

The $_SERVER['SERVER_NAME'] typically returns either the name of the server or its IP address, while $_SERVER['SERVER_SOFTWARE'] states which server software is running, such as Apache or Nginx. This may be useful in diagnostics or to configure an application with specific capabilities, depending on what your server is capable of.  

Here is how you can view information about the server:

$server_name = $_SERVER['SERVER_NAME'];
$server_software = $_SERVER['SERVER_SOFTWARE'];
echo "Server Name: " . $server_name;
echo "Server Software: " . $server_software;

Anyway, let’s move on to the next part to understand how to fetch and request specific data using $_SERVER in PHP.  

Fetching Request-Specific Details Using $_SERVER

Every time a client pulls up a page from your server, information about that request is written into a superglobal array called $_SERVER.

Of the many useful variables in there, $_SERVER['REQUEST_METHOD'] is of most note, as it shows by what method the request was made—GET, POST, and so forth.

This is crucial for form handling or varying data processing according to request type. For instance, most applications consider POST requests to be submit-type actions and GET requests to be retrieval-type actions.  

Here is an example of how the request method can be checked:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "This is a POST request.";
} else {
    echo "This is not a POST request.";
}

You can also use $_SERVER['REQUEST_URI'] to capture the URI of the request so you can tell exactly what page the user is trying to access. 

Let’s look at another key used in the $_SERVER array in the next part.  

Tracking Referring Pages Using $_SERVER

It might be very informative to track where your user came from, notably for analytics and marketing purposes.

The $_SERVER['HTTP_REFERER'] returns the URL of the referring page. However, it’s important to note that this may not always be set due to browser settings or user privacy preferences.  

Here is an example:

$referrer = $_SERVER['HTTP_REFERER'];
if ($referrer) {
    echo "User came from: " . $referrer;
} else {
    echo "No referrer information available.";
}

Below I will show you how to check secure connections using $_SERVER. Let’s move on.

Verifying HTTPS for Secure Connections using PHP $_SERVER

Security is a paramount aspect in the development of modern web applications. One of the most important factors in sensitive data handling is determining whether your site is accessed over HTTPS or not.

Through the use of $_SERVER, this can easily be achieved by determining whether the current request is secure by checking $_SERVER['HTTPS']. This is set when HTTPS is in use.  

Here is a simple check for HTTPS:

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    echo "Connection is secure.";
} else {
    echo "Connection is not secure.";
}

Now, let’s look at some ways in which $_SERVER provides information about the PHP script itself.  

Getting PHP Script Information with $_SERVER

Sometimes, you will want to know certain information about the currently running PHP script. The $_SERVER['PHP_SELF'] contains the path of the current script and is particularly useful for form actions or redirects.

So, by using $_SERVER['PHP_SELF'], you can set the form action to the current page and therefore be able to use a self-processing form.  

Here is an example:

$script_path = $_SERVER['PHP_SELF'];
echo "Current Script Path: " . $script_path;

With this, we’ve covered the basic usage of the $_SERVER array in PHP. Let’s review it with some practical examples. 

Examples of PHP $_SERVER

For example, when processing a form submission, you would want to check if $_SERVER['REQUEST_METHOD'] is POST before processing the data.

You might also use $_SERVER['HTTP_USER_AGENT'] to show different content based on the browser or device the user is using.

Another use of $_SERVER['HTTP_REFERER'] is to link back to the page the visitor was viewing after processing the form.  

Here is an example shows how you can implement a referrer-based redirect:

$referrer = $_SERVER['HTTP_REFERER'];
if ($referrer) {
    header("Location: $referrer");
    exit;
} else {
    echo "Referrer not found.";
}

Here is another example:

$ip = '';

if (isset($_SERVER['HTTP_CLIENT_IP'])) {
  $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
  $ip = $_SERVER['REMOTE_ADDR'];
}

echo $ip;

In the above script, I will only try to access each $_SERVER key if it exists, eliminating the warning. If none of these headers are set, $ip will simply be an empty string.

Wrapping UP

PHP $_SERVER is a powerhouse. It makes various server and client information—from user IP addresses to server software details and secure connection verification—accessible with ease. $_SERVER is a robust way to collect and use essential data.

Understanding how to work with $_SERVER enables you to enhance user experience, improve security, and gain insights into server-client interactions.

Knowing most of $_SERVER means you’re ready to use it in scripts for everything from diagnostics to advanced functionality.

Similar Reads

PHP if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

PHP MySQL Create Database: MySQLi & PDO Examples

If you are working with PHP and MySQL, one of the first tasks you may need is to create a…

PHP Static Property: How It Works & Examples

PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…

Understanding PHP Constants: A Simple Guide with Examples

In regard to the use of constants in PHP, clear understanding of their definition and use could be critical in…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

PHP array_find_key: How it Works with Examples

The PHP array_find_key function finds a key in an array by a condition. It checks each element and returns the…

PHP implode Function: Join Array Values into a String

The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…

Abstract Class in PHP: How It Works & Examples

Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…

PHP strpos Function: How it Works with Examples

Sometimes the string you expect is there, but strpos function gives a surprise in PHP. It may show the result…

PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…

Previous Article

PHP $GLOBALS: Access Global Variables with Examples

Next Article

PHP $_ENV: Manage Environment Variables

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.