How to Set a User Agent for PHP fopen() calls

January 21st, 2020

Warning: This post is 3 years old. Some of this information may be out of date.

Recently I had an issue where fetching an image from an URL was failing because an unknown or invalid user agent was being sent. The code was using PHP's fopen() function to fetch the image and stream it to a remote destination.

In order to set the user agent that will be used with fopen() you should set it using a php_ini setting; like this:

ini_set('user_agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:72.0) Gecko/20100101 Firefox/72.0');

Note that you can set this in the main php.ini configuration file, or set it on the fly as above.