[PHP]curl模拟表单上传文件

直接贴代码

 1 /**
2 * php curl 模拟表单上传单个文件
3 *
4 * @param type $file
5 * @param type $file_field
6 * @param type $url
7 * @param type $type
8 * @param type $post_data
9 * @return type
10 */
11 function post_file($file, $url, $file_field='file', $type='', $post_data=array(), $timeout=5) {
12 if (!file_exists($file) || !$url) {
13 return false;
14 }
15 if (!$post_data || !is_array($post_data)) {
16 $post_data = array();
17 }
18 $file = realpath($file);
19
20 $type && $file .= ';type=' . $type;
21
22 $post_data[$file_field] = '@' . $file;
23
24 $curl = curl_init();
25 curl_setopt($curl, CURLOPT_URL, $url);
26 curl_setopt($curl, CURLOPT_POST, 1);
27 curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
28 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
29 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
30 //curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0");
31 $result = curl_exec($curl);
32 curl_close($curl);
33 return $result;
34 }



posted on 2012-03-15 10:44  _seco  阅读(536)  评论(0编辑  收藏  举报

导航