代碼貼下面,唯一要注意的就是如果你的PHP版本高於5.5,在上傳文件的時候請使用new \CURLFile( arm是文件保存路徑,例如:C:\wamp64\www\dg_zhagen\public\static\Img\SS140.jpg),來設置上傳文件參數。如果低於5.5的話只要在文件路徑前面加@就行了,例如 $data = [
‘param1’ => 123,
”param2”=> 456,
“file1” => “@C:\wamp64\www\dg_zhagen\public\static\Img\SS140.jpg”,
“file2” => “@C:\wamp64\www\dg_zhagen\public\static\Img\SS148.jpg”
]
private function curl_form($post_data,$sumbit_url,$http_url){
//初始化
$ch = curl_init();
//設置變量
curl_setopt($ch, CURLOPT_URL, $sumbit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//執行結果是否被返回,0是返回,1是不返回
curl_setopt($ch, CURLOPT_HEADER, 0);//參數設置,是否顯示頭部信息,1爲顯示,0爲不顯示
curl_setopt($ch, CURLOPT_REFERER, $http_url);
//表單數據,是正規的表單設置值爲非0
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);//設置curl執行超時時間最大是多少
//使用數組提供post數據時,CURL組件大概是爲了兼容@filename這種上傳文件的寫法,
//默認把content_type設爲了multipart/form-data。雖然對於大多數web服務器並
//沒有影響,但是還是有少部分服務器不兼容。本文得出的結論是,在沒有需要上傳文件的
//情況下,儘量對post提交的數據進行http_build_query,然後發送出去,能實現更好的兼容性,更小的請求數據包。
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//執行並獲取結果
$output = curl_exec($ch);
// 釋放cURL句柄
curl_close($ch);
return $output;
}
$data = [
'CombName'=> $request->param('CombName'), //上傳參數
'PicNames' => $request->param('PicNames'),//上傳參數
'CombText' => $request->param('CombText'),//上傳參數
'CombValue' => $request->param('CombValue'),//上傳參數
'Id' => $request->param('Id'),//上傳參數
'Pwd' => $request->param('Pwd')//上傳參數
];
//$arms格式,路徑1|路徑2|路徑3|路徑4……
$arms = explode("|", $request->param('Arms'));
foreach ($arms as $arm){
//上傳文件
array_push($data,new \CURLFile($arm)); //注意:上傳文件必須要new \CURLFile($arm)($arm是文件保存路徑,例如:C:\wamp64\www\dg_zhagen\public\static\Img\SS140.jpg)
}
$res = $this->curl_form($data,$url,'');