2011-09-11 142 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