2012-02-08 21 views
1

我正在使用PHP 5.3.6,而且似乎無法使用CURL爲PUTting字符串創建PUT請求。在PHP中使用CURL編寫PUT請求

function put_data($url, $data) 
{ 
    $useragent="SimpleAgent-1.0"; 
    $fh = fopen('php://memory', 'rw'); 
    fwrite($fh, $data); 
    rewind($fh);$ch = curl_init(); 
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
    curl_setopt($ch, CURLOPT_INFILE, $fh); 
    curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data)); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_PUT, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($ch); 
    curl_close($ch); 
    fclose($fh); 

    return $result; 
} 

在這裏,$ data是我想要PUT的字符串。 不工作,返回以下錯誤:

500 Internal Server Error The server has either erred or is incapable of performing the requested operation.

expected string or buffer

+0

你的PHP有'error_log'嗎? – alex 2012-02-08 08:13:04

+0

嘗試關閉倒帶前($ fh);無論如何閱讀apache日誌 – ZiTAL 2012-02-08 08:13:17

+0

倒回後($ fh); – ZiTAL 2012-02-08 08:37:58

回答

0

我只能夠將數組作爲數據傳遞給我使用的版本。所以這就是我現在正在做的:

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE); 
curl_setopt($ch, CURLOPT_COOKIE, $curl_cookie); 
$arr = array(); 
if (isset($data)) { 
    $arr['my_data'] = $data; 
} 

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr)); 
curl_exec($ch); 
0

我用你的代碼,以便確定一個網址,並用一個字符串填充數據和所有工作按預期。被我拒絕的網站,因爲沒有接收端可以處理一個放。爲了獲取信息方便地只需要添加行 curl_setopt($ch, CURLOPT_VERBOSE, true);

,你會得到這樣的:

* About to connect() to yyyy.xxxx.com port 80 (#0) 
* Trying 62.221.196.28... 
* connected 
* Connected to yyyy.xxxx.com (zz.221.196.28) port 80 (#0) 
> PUT/HTTP/1.1 
User-Agent: SimpleAgent-1.0 
Host: yyyy.xxxx.com 
Accept: */* 
Content-Length: 14 
Expect: 100-continue 

< HTTP/1.1 100 Continue 
* We are completely uploaded and fine 
< HTTP/1.1 405 Method Not Allowed 
< Date: Thu, 09 Feb 2012 19:46:28 GMT 
< Server: Apache 
< Allow: GET,HEAD,POST,OPTIONS 
< Vary: Accept-Encoding 
< Content-Length: 231 
< Content-Type: text/html; charset=iso-8859-1 
< 
* Connection #0 to host yyy.xxxx.com left intact 
* Closing connection #0 

你可以從登錄請求看出去,但是當你想要把數據時, apache設置不允許你把數據放到那個url。因此,根據服務器的不同,您需要處理接受PUT的接收URL。

+1

嗨user1200241,你正在使用哪個版本的PHP?我發佈的代碼似乎可以在舊版本的PHP中使用。請讓我知道。 – 2012-02-10 04:34:46

+0

嗨Bijoy我沒有升級到最新的PHP 5.3.10版本,因爲我在進行其他測試時遇到內存泄漏問題。我在cli下運行你的例子,再次,最有用的擴展是詳細的選項來獲得真正的進度信息。安東 – Anton 2012-02-10 10:32:18