Host Header Injection Prevention in PHP

As a web developer, you must know about host header injection so that you can secure your web application from malicious attacks.

In this tutorial, We are going to see what is host header injection and how to prevent web apps from host header injection.

What is Host Header or HTTP Host Header?

Host header is a piece of information that can be used to identify web domain. For example host header for the URL
https://www.phpcluster.com is www.phpcluster.com.

The Host header specifies the domain name of the server.

What is Host Header Injection?

Host Header Injection is a type of web application security vulnerability which occurs when Hypertext Transfer Protocol (HTTP) headers.

Generally, we use the same web server to host several web applications on the same IP Address.
That is why the host header exists.

Host header specifies which web application should process an incoming HTTP request.

An attacker can manipulate the Host Header and cause the web application to behave in unexpected ways.

In shared hosting environments, it is possible to use this attack to force an attacker’s browser to grab resources from another virtual host on the same server. It causes Host Header injection.

How to Prevent Host Header Injection in PHP

Copy the given below code and paste in your web application common file like header

<?php
$allowed_host = array('www.phpcluster.com', 'www.demos.phpcluster.com');

if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_host)) 
{
    header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
    exit;
}
?> 

Hope you devs understood how to prevent host header inject in PHP. If you liked this article, please share with others.

Leave a Comment