php 使用 CURL 发送自定义标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13770910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending Custom Header with CURL
提问by bodesam
I want to send a request to a web service via an API as shown below, i have to pass a custom http header(Hash), i'm using CURL, my code seems to work but I'm not getting the rigth response, I'm told it has to do with the hash value, though the value has been seen to be correct, is there anything wrong with the way I'm passing it or with the code itself.
我想通过如下所示的 API 向 Web 服务发送请求,我必须传递自定义 http 标头(哈希),我使用的是 CURL,我的代码似乎可以工作,但我没有得到正确的响应,我被告知它与哈希值有关,尽管该值被认为是正确的,但我传递它的方式或代码本身是否有任何问题。
<?php
$ttime=time();
$hash="123"."$ttime"."dfryhmn";
$hash=hash("sha512","$hash");
$curl = curl_init();
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Hash:$hash'));
curl_setopt ($curl, CURLOPT_URL, 'http://web-service-api.com/getresult.xml?clientid=456&time=$ttime');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($curl);
if ($xml === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($xml);
echo htmlspecialchars("$xml", ENT_QUOTES);
?>
回答by RafaSashi
If you need to get and set custom http headers in php, the following short tutorial is really useful:
如果您需要在 php 中获取和设置自定义 http 标头,以下简短教程非常有用:
Sending The Request Header
发送请求头
$uri = 'http://localhost/http.php';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('X-User: admin', 'X-Authorization: 123456'),
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
// echo response output
echo $out;
Reading the custom header
读取自定义标题
print_r(apache_request_headers());
you should see
你应该看到
Array
(
[Host] => localhost
[Accept] => */*
[X-User] => admin
[X-Authorization] => 123456
[Content-Length] => 9
[Content-Type] => application/x-www-form-urlencoded
)
Custom Headers with PHP CGI
使用 PHP CGI 自定义标头
in .htaccess
在.htaccess中
RewriteEngine On
RewriteRule .? - [E=User:%{HTTP:X-User}, E=Authorization:%{HTTP:X-Authorization}]
Reading the custom headers from $_SERVER
从 $_SERVER 读取自定义标头
echo $_SERVER['User'];
echo $_SERVER['Authorization'];
Resources
资源
回答by dev-null-dweller
'Hash:$hash'should be either "Hash: $hash"(double quotes) or 'Hash: '.$hash
'Hash:$hash'应该是"Hash: $hash"(双引号)或'Hash: '.$hash
The same goes for your URL passed in CURLOPT_URL
传入的 URL 也是如此CURLOPT_URL

