我是 PHP 新手,正在尝试调用 REST 服务。我可以使用 PHP 中的 Curl 或 Guzzle 客户端来做到这一点。稍后我会从 Mozilla 和 Chrome 浏览器调用它。
问题是 Guzzle 和 Curl 没有将实际的 User-Agent 标头作为请求标头转发到后端服务。
默认 Guzzle
User-Agent header is Guzzle/ver curl/ver PHP/ver
我知道我们可以在 Curl 和 Guzzle 中添加自定义/硬编码标头。但我不想硬编码。
<?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>
当我从 Chrome/Mozilla/Mobile/Safari 调用 PHP 服务时,我希望将相应的
user-agent
标头作为请求标头发送到后端服务。
是否有办法以任何方式做到这一点?
PHP 有一个内置数组,用于存储请求中的数据 -
$_SERVER['HTTP_USER_AGENT']
。
然后您可以使用
user-agent
选项设置
headers
guzzle 用途。
$client->request('GET', '/get', [
'headers' => [
'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
]
]);
对于 GuzzleHttp\Client:
$client = new GuzzleHttp\Client([
'headers' => [
'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
]
]);
$res = $client->request('GET', 'http://sample.com');
或
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://sample.com', [
'headers' => [
'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
]
]);
对于 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'],
));
curl_setopt($curl, CURLOPT_USERAGENT, $agent);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
希望这对某人有帮助