3

我有一段命令行 curl 代码,我想将其翻译成 php。我正在挣扎。

这是代码行

$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member

大字符串将是我要传递给它的变量。

这在 PHP 中是什么样子的?

4

3 回答 3

3

您首先需要分析该行的作用:

$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member

这并不复杂,您可以在curl 的手册页上找到所有开关的说明:

-H, --header <header>: (HTTP) 获取网页时使用的额外标头。您可以指定任意数量的额外标头。[...]

curl_setopt_array您可以通过 PHP 中的Docs添加标题(所有可用选项在curl_setoptDocs中进行了说明):

$ch = curl_init('https://api.service.com/member');
// set URL and other appropriate options
$options = array(        
    CURLOPT_HEADER => false,
    CURLOPT_HTTPHEADER => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
);
curl_setopt_array($ch, $options);
curl_exec($ch); // grab URL and pass it to the browser
curl_close($ch);

如果 curl 被阻止,您也可以使用 PHP 的 HTTP 功能来做到这一点,即使 curl 不可用(如果 curl 在内部可用,则需要 curl):

$options = array('http' => array(
    'header' => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
));
$context = stream_context_create($options);
$result = file_get_contents('https://api.service.com/member', 0, $context);
于 2012-05-01T09:02:22.697 回答
1

您应该查看 php.ini 中的curl_*函数。curl_setopt()您可以设置请求的标头。

于 2012-05-01T08:57:42.897 回答
1

1)你可以使用卷曲功能

2)你可以使用exec()

exec('curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member');

3)如果您只想将信息作为字符串,则可以使用file_get_contents() ...

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Authorization: 622cee5f8c99c81e87614e9efc63eddb"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.service.com/member', false, $context);
?>
于 2012-05-01T08:58:40.213 回答