2011-09-11 138 views
0

我在嘗試發佈一些數據時需要上傳一個文件(圖像)。使用PHP 5.3.3和CURL 7.20.0。用PHP和cURL上傳圖像

這裏是php腳本(該圖像位於相同的文件夾中,我已檢查路徑是否有效)。

function curl_post_request($url, $data, $referer='') { 
$data = http_build_query($data); // seems to be required arrays should'nt be supported ? whatever. 
$c = curl_init(); 
curl_setopt($c, CURLOPT_URL, $url); 
curl_setopt($c, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($c, CURLOPT_HEADER, true); 
curl_setopt($c, CURLOPT_POST, true); 
curl_setopt($c, CURLOPT_POSTFIELDS, $data); 
curl_setopt($c, CURLOPT_REFERER, $referer); 
curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); 
curl_setopt($c, CURLOPT_HEADER, $headers); 
curl_setopt($c, CURLINFO_HEADER_OUT, true); 
curl_setopt($c, CURLOPT_VERBOSE, true); 
$output = curl_exec($c); 
var_dump(curl_getinfo($c, CURLINFO_HEADER_OUT)); 
//var_dump($data); 
if($output === false) trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING); 
curl_close($c); 
return $output; 
} 

if(isset($_GET['GO'])) { 

$data = array(
'pic1' => "@".realpath('image.jpg'), 
'postedvar1' => 'test1', 
'postedvar2' => 'test2' 
); 
$url = 'http://localhost/test/index.php'; 
$a = curl_post_request($url, $data); 
var_dump($a); 

} else { 

print_r($_POST); 
print_r($_FILES); 
} 

我錯過了什麼?這是爲你們工作嗎?

捲曲請求似乎是細,看看下面的結果:

 
    headers = POST /test/test.php HTTP/1.1 
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1 
    Host: localhost 
    Accept: */* 
    Referer: 
    Content-Length: 82 
    Content-Type: application/x-www-form-urlencoded 

    HTTP/1.1 200 OK 
    Date: Sun, 11 Sep 2011 19:46:18 GMT 
    Server: Apache/2.2.16 (Win32) PHP/5.3.3 
    X-Powered-By: PHP/5.3.3 
    Content-Length: 138 
    Content-Type: text/html 

    $_POST = Array(
    [pic1] => @C:\wamp\www\test\image.jpg 
    [postedvar1] => test1 
    [postedvar2] => test2 
    ) 
    $_FILES = Array() 
+1

你什麼錯誤?來自'curl_error()'的任何內容? –

+0

$ _POST確定,但$ _FILES爲空! arobase似乎對請求沒有影響。請求似乎沒有任何文件就可以正常工作! –

+0

請不要用「問題已解決!」來解決您的問題。 - StackOverflow旨在成爲未來的資源,以及現在爲您提供幫助。 – salathe

回答

1

要使用指定要上傳的文件的@filepath方法中,對於CURLOPT_POSTFIELDS選項的值必須保持作爲陣列。

curl_post_request()函數的第一行將數組轉換爲urlencoded字符串。

CURLOPT_POSTFIELDS說明書中的描述 - http://php.net/curl-setopt