使用PHP和cURL上传图像

时间:2011-09-11 19:40:21

标签: php image post curl upload

我试图用一个我要上传的文件(图像)发布一些数据时遇到麻烦。使用PHP 5.3.3和CURL 7.20.0。

这是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 个答案:

答案 0 :(得分:1)

要使用指定要上载的文件的@filepath方法,CURLOPT_POSTFIELDS选项的值必须保留为数组。

curl_post_request()函数的第一行将数组转换为urlencoded字符串。

请参阅手册中的CURLOPT_POSTFIELDS说明 - http://php.net/curl-setopt