使用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);
?>