Understanding php $_server ‘http_host’: A Comprehensive Guide for Devs

As a developer, you know that the $_SERVER['HTTP_HOST'] is a commonly used PHP superglobal that refers to the host name of the server where the current request is being executed. In this article, we will dive deeper into the concept and explore its various applications. So, Devs, sit tight and let’s get started!

What is $_SERVER[‘HTTP_HOST’]?

The $_SERVER['HTTP_HOST'] is a PHP global variable that returns the domain name of the server where the current script is running. It is a superglobal because it is available in all scopes of your script, including functions, classes, and global code. This variable is part of the $_SERVER array, which contains information about the server environment and the request made by the client.

Most often, $_SERVER['HTTP_HOST'] is used to construct links and URLs in your script. It contains the domain name with optional port number, so you can use it to create absolute URLs that point to the same server where the script is executed. For example:

Code
Result
echo $_SERVER['HTTP_HOST'];
example.com
$url = "http://" . $_SERVER['HTTP_HOST'] . "/path/to/file.php";
http://example.com/path/to/file.php

How does $_SERVER[‘HTTP_HOST’] work?

When a user requests a web page from a server, the server receives the request and processes it by running a script. The script may need to know the domain name of the server in order to respond appropriately to the request. For example, if the script generates a link to another page on the same server, it needs to know the domain name of the server so it can construct an absolute URL that works correctly.

The $_SERVER['HTTP_HOST'] variable is populated by the server when the script is executed. Specifically, it is populated with the value of the HTTP Host header sent by the client. This header contains the domain name of the server that the client wants to access, and it is mandatory for HTTP/1.1 requests.

If the client sends a request without a Host header, the server may use a default domain name or return an error response, depending on its configuration. Therefore, it is important to always include a Host header when sending HTTP/1.1 requests.

Common Applications of $_SERVER[‘HTTP_HOST’]

Building Absolute URLs

One of the most common uses of $_SERVER['HTTP_HOST'] is to construct absolute URLs in your script. An absolute URL includes the scheme (e.g. http), domain name, and path of a resource, and can be used to link to pages or resources on the same server or on remote servers.

To build an absolute URL in PHP, you typically concatenate the $_SERVER['HTTP_HOST'] variable with the desired path and query string. For example:

Code
Result
$url = "http://" . $_SERVER['HTTP_HOST'] . "/path/to/file.php";
http://example.com/path/to/file.php
$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
https://example.com/path/to/file.php?param=value

In the first example, we construct an absolute URL that points to a file named file.php located in a subdirectory of the root directory of the server. We use the http scheme to indicate that the resource is accessed over HTTP.

In the second example, we construct an absolute URL that points to the current script, including any query parameters that were included in the request. We use the https scheme to indicate that the resource is accessed over HTTPS, which is a secure protocol for transferring data over the internet.

Virtual Hosting

Another common application of $_SERVER['HTTP_HOST'] is in virtual hosting setups. Virtual hosting is a technique that allows multiple websites to share the same server resources by assigning each website a unique domain name and a separate directory for storing its files.

When a request is made for a virtual host, the server uses the $_SERVER['HTTP_HOST'] variable to determine which website the request is intended for. It then maps the requested URL to the appropriate directory on the server and executes the appropriate script or serves the requested file.

Virtual hosting is a powerful technique that can greatly reduce the cost and complexity of hosting multiple websites on the same server. It is widely used by shared hosting providers and large organizations that host many websites on a single server.

READ ALSO  Starmade: How to Host a Server

Domain Name Parsing and Validation

The $_SERVER['HTTP_HOST'] variable can also be used for parsing and validating domain names in your script. It contains the domain name with optional port number, so you can use it to extract the domain name and validate it against a list of allowed domain names or patterns.

For example, you can use the parse_url() function to extract the domain name from a URL string and check if it matches a list of allowed domain names:

Code
Result
$url = "http://example.com/path/to/file.php";
$parsed_url = parse_url($url);
array(
   "scheme" => "http",
   "host" => "example.com",
   "path" => "/path/to/file.php"
);
$allowed_domains = array("example.com", "example.net");
if(in_array($parsed_url['host'], $allowed_domains)) {
   // domain name is allowed
}

In this example, we first parse a URL string using the parse_url() function, which returns an associative array of its components. We then extract the domain name from the array using the 'host' key and check if it is included in a list of allowed domain names.

FAQ

What is the difference between $_SERVER[‘HTTP_HOST’] and $_SERVER[‘SERVER_NAME’]?

Both $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'] refer to the domain name of the server where the current script is running. However, the main difference is in how they are populated and what they contain.

The $_SERVER['HTTP_HOST'] variable is populated with the value of the HTTP Host header sent by the client, which can be manipulated by malicious users or intermediaries. It contains the domain name with optional port number, as received in the request.

The $_SERVER['SERVER_NAME'] variable, on the other hand, is populated by the server configuration and contains the canonical name of the server as specified in the configuration files. It does not include any port number information and is less susceptible to manipulation by external sources.

Which one should you use? It depends on your use case. If you want to construct URLs or links based on the host name received in the client request, then use $_SERVER['HTTP_HOST']. If you want to refer to the actual server name as specified in the configuration, then use $_SERVER['SERVER_NAME'].

How do you handle requests that don’t include a Host header?

If a client sends a request without a Host header, the server may interpret it in different ways depending on its configuration. Some servers may return an error response, some may use a default domain name or IP address, and some may simply ignore the request.

To ensure that your script works correctly in all cases, you should always include a check for the Host header before using $_SERVER['HTTP_HOST']. If the header is missing or empty, you can either use a default domain name or IP address, or return an error response to the client.

For example:

Code
Result
if(empty($_SERVER['HTTP_HOST'])) {
   header("HTTP/1.1 400 Bad Request");
   exit();
}
$domain = $_SERVER['HTTP_HOST'] ?: "default.com";
$url = "http://" . $domain . "/path/to/file.php";

In this example, we first check if the Host header is empty or missing using the empty() function. If it is, we return a 400 Bad Request response to the client using the header() function and exit the script.

We then assign a default value of default.com to the $domain variable using the ?: operator, which returns the first non-empty value from its operands. Finally, we use the domain name to construct an absolute URL for the desired resource.

How do you sanitize user inputs that contain $_SERVER[‘HTTP_HOST’]?

If your script accepts user input that may contain $_SERVER['HTTP_HOST'], you should always sanitize the input to prevent malicious users from injecting arbitrary values into your script. This is especially important if you use the input to construct URLs or execute shell commands.

To sanitize user input in PHP, you can use the following functions:

  • filter_var() – validates and sanitizes a single variable using a specified filter
  • filter_input() – retrieves and sanitizes a specific input variable based on its type and name
  • htmlspecialchars() – converts special characters to HTML entities to prevent XSS attacks

For example, you can use the filter_var() function to sanitize an input variable that should contain a valid domain name:

READ ALSO  How to Troubleshoot "Destination Host Unreachable" Error on Ubuntu Server
Code
Result
$input = $_POST['domain'];
$sanitized = filter_var($input, FILTER_SANITIZE_URL);
$host = parse_url($sanitized, PHP_URL_HOST);
$url = "http://" . htmlspecialchars($host) . "/path/to/file.php";

In this example, we first retrieve an input variable named domain using the $_POST superglobal. We then sanitize the input using the FILTER_SANITIZE_URL filter, which removes any characters that are not allowed in a URL. We then extract the domain name from the sanitized URL using the parse_url() function, and finally use the domain name to construct an absolute URL for the desired resource.

Conclusion

Now that you have a better understanding of the $_SERVER['HTTP_HOST'] variable, you can use it confidently in your PHP scripts to construct links and URLs, handle virtual hosting, and parse and validate domain names. Remember to always sanitize user inputs and handle requests with missing or invalid Host headers to ensure the security and stability of your applications.