$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_SAFE_UPLOAD, false); //php5.6要加上这个 $fields = array(); $fields ['file'] = '@' . $file; curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_POST, 1 ); curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); $response = curl_exec ( $ch );
php5.6之前上传图片和同时传数组的例子:
$file = __DIR__ .'/1.jpg;type=image/jpeg'; $data = array( 'w_type' => 1, 'w_ip' => '111.111.111.111', 'eqroom_id' => 104, 'eqroom_name' => '南宁机房', 'w_domain[0]' => 'baidu.com', 'w_domain[1]' => 'weibo.com', 'w_contacts_man' => '陈活跃', 'w_contacts_phone' => '134329xx545', 'w_shengid' => '110000', 'w_shiid' => '110100', 'w_xianid' => '110101', 'w_address' => '红旗北路', 'w_certificate' => 1, 'w_certificate_no' => '440902xxxx1017081X', 'w_certificate_file' => '@' . $file, ); $result = curlUpload($url, $data);
图片路径需加上 type ,要不后台接收到的图片类型为错的。
/** * CURL的Upload请求 * * @param string $url 请求的URL地址 * @param array $data 请求的参数 * @return string */ function curlUpload($url, $data=array()) { //$data = http_build_query($data); //如果不是上传文件的,需要加上这个 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); //curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); //php5.6要加上这个 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec($ch); curl_close($ch); return $result; }