【问题标题】:Upload image with PHP and cURL使用 PHP 和 cURL 上传图片
【发布时间】:2011-11-14 21:29:57
【问题描述】:

我在尝试使用要上传的一个文件(图像)发布一些数据时遇到问题。使用 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);
}

我错过了什么?这对你们有用吗?

curl请求好像没问题,看看下面的结果:

标头 = POST /test/test.php HTTP/1.1 用户代理:Mozilla/5.0(Windows;U;Windows NT 5.1;en-US;rv:1.8.1.1)Gecko/20061204 Firefox/2.0.0.1 主机:本地主机 接受: */* 推荐人: 内容长度:82 内容类型:application/x-www-form-urlencoded HTTP/1.1 200 正常 日期:2011 年 9 月 11 日星期日 19:46:18 GMT 服务器:Apache/2.2.16 (Win32) PHP/5.3.3 X-Powered-By: PHP/5.3.3 内容长度:138 内容类型:文本/html $_POST = 数组( [pic1] => @C:\wamp\www\test\image.jpg [postedvar1] => test1 [postedvar2] => test2 ) $_FILES = 数组()

【问题讨论】:

  • 您遇到什么错误?来自curl_error()的任何东西?
  • $_POST 可以,但 $_FILES 为空! arobase 似乎对请求没有影响。没有任何文件,请求似乎很顺利!
  • 请不要用“问题已解决!”来回答您的问题。 — StackOverflow 旨在成为未来的资源,并立即为您提供帮助。

标签: php image post curl upload


【解决方案1】:

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

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

参见手册中CURLOPT_POSTFIELDS的描述——http://php.net/curl-setopt

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2015-01-17
    相关资源
    最近更新 更多