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 Loop: How Loops Work with Examples

A loop in PHP helps you run tasks without repeating the same lines. In this article, you will learn how…

PHP abs Function: How to Get Absolute Values

The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…

PHP MySQL ORDER BY: How to Sort Data in SQL?

Sorting data is one of those things we do all the time but rarely stop to think about. Whether you…

PHP str_replace Function: How it Works with Examples

If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

PHP array_diff_uassoc: How to Compare Arrays with Keys

PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…

PHP Data Types: Understanding the 10 Primitive Types

The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…

PHP Null: How to Assign and Check for Null Values

PHP introduced null to handle undefined or missing values. It helps prevent errors when you check if a variable exists.…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP Variadic Functions: Use Unlimited Arguments

PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed…

PHP Switch | How the Switch Statement Works in PHP

The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

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.