Skip to content

Instantly share code, notes, and snippets.

@vyspiansky
Last active April 25, 2024 08:39
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vyspiansky/82f4b1ef6fcff160047d to your computer and use it in GitHub Desktop.
Save vyspiansky/82f4b1ef6fcff160047d to your computer and use it in GitHub Desktop.
PHP: set user agent using file_get_contents()
<?php
$options = array('http' => array('user_agent' => 'custom user agent string'));
$context = stream_context_create($options);
$response = file_get_contents('http://domain/path/to/uri', false, $context);
@emiremen
Copy link

Thank you very much that is what I was looking for. It worked very well.

@wosetwo
Copy link

wosetwo commented Oct 4, 2020

Other option: https://stackoverflow.com/a/13969212/14389431

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);

@jonkerw85
Copy link

Great, thanks!

@mikenk2010
Copy link

Works like a charm!!! 🥰

@burkybang
Copy link

This was helpful to me. Thanks!

@hgc81538
Copy link

Or set it globally

ini_set('user_agent', 'SomeBrowser v42.0.4711');

$response = file_get_contents('http://domain/path/to/uri');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment