PHP: Set cURL User Agent

This PHP tutorial will show you how to set a custom user agent with cURL.

To modify the User-Agent request header, you will need to use the CURLOPT_USERAGENT option.

PHP allows you to configure cURL-related options using the curl_setopt function:

$url = "http://test.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, "My User Agent");

CURLOPT_USERAGENT sets the contents of the “User-Agent: ” header, which will be attached to your HTTP request.

In the example above, we set it to “My User Agent”.

What is the default cURL User-Agent in PHP?

By default, PHP will set the user agent to “cURL”, followed by the version you have installed.

For example, it may be “cURL/7.81” or “cURL/8.5.0”.

Why would I need to change it?

Servers may block requests that contain unidentified user agents. They may also disable certain features or display error messages about the browser being out of date.

By setting a custom user agent, you can fool these servers into thinking that your HTTP request came from a legitimate, up-to-date browser.

The following cURL request imitates the Firefox browser:

$userAgent = 'Mozilla/5.0 (Android 13; Mobile; rv:120.0) Gecko/120.0 Firefox/120.0';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

The user agent above will tell the server that we are using Firefox version 120 on an Android device.

Other examples of common user agents:

  • Chrome: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
  • Internet Explorer 10: Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)
  • Internet Explorer 6: Mozilla/4.08 (compatible; MSIE 6.0; Windows NT 5.1)
  • Googlebot: Googlebot/2.1 (+http://www.google.com/bot.html)
  • Bingbot: Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)
  • IE 11: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
  • Opera: Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14
  • Safari: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A
  • Twitter: Twitterbot/1.0
  • Facebook: facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)
  • Microsoft Edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/119.0.2151.97

As you can see, there are an almost endless number of user agents. Each platform and browser may contain something different. There are also various bots.

Don’t trust user agents.

The PHP examples above illustrate why you can never trust user agent data. Like all fields in an HTTP request, it can be easily changed.

$userAgent = $_SERVER['HTTP_USER_AGENT'];

The $userAgent variable above will contain whatever the client has sent to the server. Therefore, you should not use it for security purposes.