使用curl 提交表單(多維陣列+檔案)資料到伺服器的有關問題

來源:互聯網
上載者:User
使用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',

------解決方案--------------------

$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);

?>
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.