BLOG // June 7, 2021
Set a custom user agent with Laravel's Http Client
You can customize the user agent that Laravel sends with the withUserAgent
call. It can often happen that a WAF or other security system will block curl, PHP and Guzzle based requests. In my example below you can see that I am setting it to be a recent version of Chrome:
$agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36';
$response = Http::withUserAgent($agent)
->timeout(5)
->get($url);
A useful tool when finding recent browser user agents is the What Is My Browser site. They maintain a list of the latest common Chrome user agents on the link I gave, which is what I would recommend using.
Comments
Subscribe to new articles
If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.