How to prevent host header attack in Laravel

Updated 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