2010-10-18 96 views
24

我能夠成功運行下面的curl命令(在命令行):使用PUT方法與PHP curl庫

curl -XPOST --basic -u user:password -H accept:application/json -H Content-type:application/json --data-binary '{ "@queryid" : 1234 }' http://localhost/rest/run?10 

下面是我在做什麼,到目前爲止似乎但是它不

$headers = array(
    'Accept: application/json', 
    'Content-Type: application/json', 
); 

$url = 'http://localhost/rest/run?10'; 
$query = '{ "@queryid" : 1234 }'; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, "user:password"); 

curl_setopt($ch, CURLOPT_PUT, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $query); 
curl_setopt($ch, CURLOPT_POSTFIELDSIZE, strlen($query)); 

$output = curl_exec($ch); 

echo $output; 

什麼是試圖轉換--data二進制使用PUT方法時,正確的方法:與REST服務我使用的是工作?

回答

41

創建磁盤上的臨時文件,而不是你可以使用php://temp

$body = 'the RAW data string I want to send'; 

/** use a max of 256KB of RAM before going to disk */ 
$fp = fopen('php://temp/maxmemory:256000', 'w'); 

if (!$fp) 
{ 
    die('could not open temp memory data'); 
} 

fwrite($fp, $body); 
fseek($fp, 0); 

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer 
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));        

的好處是沒有磁盤IO所以它應該是您的服務器上更快,更負載。

+1

這太棒了!我不知道臨時的FD,它幫助我加載了一個curl上傳的YouTube上傳文件(將剩餘的字節讀入mem,然後使用你的方法正常上傳) – 2012-06-11 16:41:22

+0

模式不應該是'w +'嗎? – flm 2013-09-04 20:27:51

34

大家好我得到它的工作使用此配置:

// Start curl 
$ch = curl_init(); 
// URL for curl 
$url = "http://localhost/"; 

// Clean up string 
$putString = stripslashes($query); 
// Put string into a temporary file 
$putData = tmpfile(); 
// Write the string to the temporary file 
fwrite($putData, $putString); 
// Move back to the beginning of the file 
fseek($putData, 0); 

// Headers 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
// Binary transfer i.e. --data-BINARY 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_URL, $url); 
// Using a PUT method i.e. -XPUT 
curl_setopt($ch, CURLOPT_PUT, true); 
// Instead of POST fields use these settings 
curl_setopt($ch, CURLOPT_INFILE, $putData); 
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString)); 

$output = curl_exec($ch); 
echo $output; 

// Close the file 
fclose($putData); 
// Stop curl 
curl_close($ch); 

:)

+2

+1感謝您花時間回來並回答您自己的問題。您爲我節省了很多時間 – Basic 2012-08-10 13:29:13

5

所有需要設置的都是重用post方法的自定義請求。

CURLOPT_URL=>$url, 
CURLOPT_CUSTOMREQUEST=>'PUT', 
CURLOPT_POSTFIELDS=>$params, 
+0

當訪問REST API時,這個指針對我很有幫助,其中沒有實際的數據在請求中傳輸(url包含參數) – Loopo 2015-01-06 11:33:52

+0

這個方法使得通過PUT的通話更加容易。沒有文件色彩,只需使用POST基礎結構。 – kratenko 2015-02-25 17:00:23

+0

你救了我... upvoted ... – 2015-11-06 17:56:36