• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

使用curl 提交表单(多维数组+文件)数据到服务器的问题

php 搞代码 3年前 (2022-01-23) 35次浏览 已收录 0个评论

我在本地搭了一个测试服务器,Apache+PHP,想使用curl自动提交表单数据到远程服务器。

远程服务器表单有两项数据需要提交:
1、input file: 要求传图片
2、checkbox: 会有多个按钮被选中

问题:
运行时下面程序时checkbox数组会被转成字符串,程序报错如下:
Array to string conversion

主要代码如下:

$post_url = "http://domain.com/post.php";
$post_data = array(
'color' => array('red', 'green', 'blue'),
'img' => "@d:\image.jpg"
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($post_data));
if (false === curl_exec($ch)) {
echo "Curl_error: " . curl_error($ch);
}
curl_close($ch);

尝试过:
1、如果用http_build_query处理$post_data,那么color数组就可以正确的传到服务器,但是文件也会被当成一般query参数,从而上传失败。
2、如果不使用http_build_query,文件可以正确上传,但是在服务器抓到color数组的值就是"Array",并提示"Array to string conversion"错误。
3、我在php.net上看curl手册,发现有个家伙跟我的情况有点类似,但是他使用的是关联数组,所以可以绕弯,类似
$post_data = array("method" => $_POST["method"],
"mode" => $_POST["mode"],
"product[name]" => $_POST["product"],
"product[cost]" => $_POST["product"]["cost"],
"product[thumbnail]" => "@{$_FILES["thumbnail"]["tmp_name"]}");
即可解决,可是我的情况是索引数组,模仿他的样子写了之后仍然无效。

请教各位朋友是否知道如何解决?
[解决办法]
'color' => array('red', 'green', 'blue'),
写作
'color' => http_build_query(array('red', 'green', 'blue')),
不行吗?

写成这样更好
'color[0]' => 'red',
'color[1]' => 'green',
'color[2]' => 'blue',

[解决办法]

<?php$post_url = "http://localhost/test/test1.php";    $post_data = array(        'a[1]' => 'red',        'b[2]' => 'red',        'c[3]' => 'red',               'e[1]' => "@d:\img.gif",        'e[2]' => "@d:\\2.gif"    );      //通过curl模拟post的请求;function SendDataByCurl($url,$data=array()){    //对空格进行转义    $url = str_replace(' ','+',$url);    $ch = curl_init();    //设置选项,包括URL    curl_setopt($ch, CURLOPT_URL, "$url");    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_set<a style="color:transparent">本@文来源gao($daima.com搞@代@#码(网5</a><strong>搞gaodaima代码</strong>opt($ch, CURLOPT_HEADER, 0);    curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟       // POST数据    curl_setopt($ch, CURLOPT_POST, 1);    // 把post的变量加上    curl_setopt($ch, CURLOPT_POSTFIELDS, ($data));    //所需传的数组用http_bulid_query()函数处理一下,就ok了        //执行并获取url地址的内容    $output = curl_exec($ch);    $errorCode = curl_errno($ch);    //释放curl句柄    curl_close($ch);    if(0 !== $errorCode) {        return false;    }    return $output;}$url = "http://localhost/test/test1.php";//通过curl的post方式发送接口请求echo  SendDataByCurl($url,$post_data);?>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用curl 提交表单(多维数组+文件)数据到服务器的问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址