Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic user-agent header using PHP Curl or Guzzle Client

I am new to PHP and trying to call a REST Service. I could do that using either Curl or Guzzle Client in PHP. Later I am calling this from Mozilla and Chrome Browser.

The problem is Guzzle and Curl are not forwarding the actual User-Agent header as Request Header to the backend services.

The default Guzzle User-Agent header is Guzzle/ver curl/ver PHP/ver

I know we can add custom/hardcoded headers in both Curl and Guzzle. But I dont want to hardcode.

<?php 
require './vendor/autoload.php';
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://sample.com');
$data = json_decode($res->getBody(), true); 
//echo  $res->getBody()  
?> 

<html>
<body>
    <p>Body  is  <?php echo  $res->getBody() ?> </p>
</body>
</html>

When I call the PHP service from either Chrome/Mozilla/Mobile/Safari, I want the respective user-agent headers to be sent as request headers to backend services.

If there a way to do this in any way?

like image 629
John Seen Avatar asked Oct 27 '25 04:10

John Seen


2 Answers

PHP has a build-in array which stores data from request -$_SERVER['HTTP_USER_AGENT'].

You can then set the user-agent guzzle uses with the headers option.

$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
    ]
]);
like image 51
Somrlik Avatar answered Oct 28 '25 18:10

Somrlik


For GuzzleHttp\Client:

$client = new GuzzleHttp\Client([
    'headers' => [
        'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
    ]
]);
$res = $client->request('GET', 'http://sample.com');

or

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://sample.com', [
    'headers' => [
        'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
    ]
]);

For php cUrl:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL            => 'http://sample.com',
  CURLOPT_TIMEOUT        => 0,
  CURLOPT_CUSTOMREQUEST  => 'GET',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Hope this helps for someone

like image 28
The Manh Nguyen Avatar answered Oct 28 '25 18:10

The Manh Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!