2012-05-01 149 views
3

我有一个命令行curl代码,我想要翻译成php。我正在挣扎。如何将此命令行curl转换为php curl?

这里的代码

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

大的字符串将是一个变量我进入这行了。

这在PHP中看起来如何?

回答

3

您首先需要分析该行的功能:

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

它并不复杂,你会发现所有的交换机上curl's manpage解释说:

-H, --header <header>:(HTTP)额外头得到一个网页时使用。您可以指定任何数量的额外标题。 [...]

您可以通过PHP添加curl_setopt_arrayDocs头(所有可用的选项都在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); 

在卷曲的情况下被阻止,你可以做到这一点也与PHP的HTTP功能,即使卷曲不可用其中工程(如果卷曲可用它需要卷曲内部):

$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

你应该看看在curl_*函数。 使用curl_setopt()您可以设置请求的标题。

1

1)你可以使用Curl functions

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

假设您熟悉PHP cURL functions,您可以使用curl_setopt()可以在您的请求中传递任何HTTP标头:

<?php 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://api.service.com/member"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: 622cee5f8c99c81e87614e9efc63eddb")); 
curl_exec($ch);