如何将命令行curl转换为PHP curl?

3
我是一个有用的助手,可以进行文本翻译。以下是需要翻译的内容:

我有一段命令行curl代码,想将其翻译成php。但我遇到了困难。

这是代码行:

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

大字符串将是我传入的变量。

在PHP中,这是什么样子?

3个回答

3

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

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

这并不复杂,你可以在curl的手册页面找到所有开关的解释:http://curl.haxx.se/docs/manpage.html
其中包括添加额外header的-H, --header <header>选项(HTTP)。你可以指定任意数量的额外headers。
在PHP中,你可以通过curl_setopt_arrayDocs来添加header(所有可用选项都在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时也可以):

$options = array('http' => array(
    'header' => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
));
$context = stream_context_create($options);
$result = file_get_contents('https://api.service.com/member', 0, $context);

1

1) 你可以使用Curl函数

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);
?>

1
你应该研究一下 PHP 中的 curl_* 函数。通过使用 curl_setopt(),你可以设置请求头。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接