如何在 php 中使用 curl 将访问密钥作为 HTTP 标头传递
问题描述:
如何在 PHP 中发送下面提到的 CURL 请求?我将在 php 中使用哪些函数?
How can i send a CURL request mentioned below in PHP? What functions i will use in php?
$ curl -H 'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0' \
-H 'Accept: application/json' \
'http://example.sifterapp.com/api/projects'
我试过这个代码..但它不起作用..请做需要的
I have tried this code.. but its not working.. Please do the needful
$curlString = "";
$curlString .= "-H \"X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0\" \";
$curlString .= "-H \"Accept: application/json\" \";
$url="http://example.sifterapp.com/api/projects";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlString);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
答
您没有正确使用 CURLOPT_HTTPHEADER
.来自手册:
You do not use correctly CURLOPT_HTTPHEADER
. From the manual:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER 要设置的 HTTP 标头字段的数组,在format array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_HTTPHEADER An array of HTTP header fields to set, in the format
array('Content-type: text/plain', 'Content-length: 100')
所以你需要:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0',
'Accept: application/json',
));