Search code examples
phpuser-agentguzzlephp-curl

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?


Solution

  • 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'],
        ]
    ]);