How to prevent host header attack in Laravel

Created at 20-Oct-2021 , By samar

How to prevent host header attack in Laravel

In this session, we will try our hand at solving the "How to prevent host header attack in Laravel".

You can prevent host header attack in Laravel. You have to simply implement provided code snippet in boot method of AppServiceProvider class. It will prevent host header attack in Laravel application.
  • Prevent host header attack using PHP script in Laravel

    $allowed_host = array('www.w3codegenerator.com');
    
    if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_host)) 
    {
        header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
        exit;
    }
    

    Place this code snippet in boot method of AppServiceProvider class in app\Providers\AppServiceProvider.php. You have to change the domain name as per your requirments in $allowed_host array. Different format for your domains could be like : www.w3codegenerator.com, w3codegenerator.com , subdomain.w3codegenerator.com

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.