dongze5043 2019-02-08 05:43
浏览 254
已采纳

如何使用PHP Curl或Guzzel 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?

  • 写回答

1条回答 默认 最新

  • dsgk40568 2019-02-08 05:50
    关注

    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'],
        ]
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog