2012-05-01 145 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);