当前位置: 代码迷 >> PHP >> 使用curl 提交表单(多维数组+文件)数据到服务器的有关问题
  详细解决方案

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

热度:391   发布时间:2016-04-28 20:20:33.0
使用curl 提交表单(多维数组+文件)数据到服务器的问题
我在本地搭了一个测试服务器,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_setopt($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);

?>