CURL 多线程 foreach多个文件上传

$dir = 'dist302';
$files = read_dir($dir);
function read_dir($dir){  
    $files=array();  
    $dir_list=scandir($dir);  
    foreach($dir_list as $file){  
        if($file!='..' && $file!='.'){  
            if(is_dir($dir.'/'.$file)){  
                $files[]=read_dir($dir.'/'.$file);  
            }else{  
                $files[]=$file;  
            }  
        }  
    }  
    return $files;  
}


doUpload($files,$dir);


function doUpload($array = array(),$dir){
    $wait_usec = 0;//intval($wait_usec);
    $data    = array();
    $handle  = array();
    $running = 0;
    $mh = curl_multi_init(); // multi curl handler
    $i = 0;
    $url = 'http://www.baidu.com';
    foreach($array as $file) {
$filename =realpath($dir.'/'.$file);
$minetype = 'image/jpeg';
$curl_file = curl_file_create($filename,$minetype);
$post_data = array(
	'fileName' => $file,
	'user_file'=>$curl_file 
);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return don't print
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_MAXREDIRS, 7);
		//设置post方式提交
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);	
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//设置超时时间
        curl_multi_add_handle($mh, $ch); // 把 curl resource 放进 multi curl handler 里
        $handle[$i++] = $ch;
    }
    /* 执行 */
    do {
        curl_multi_exec($mh, $running);
        if ($wait_usec > 0) /* 每个 connect 要间隔多久 */
            usleep($wait_usec); // 250000 = 0.25 sec
    } while ($running > 0);
    /* 读取资料 */
    foreach($handle as $i => $ch) {
        $content  = curl_multi_getcontent($ch);
        $data[$i] = (curl_errno($ch) == 0) ? $content : false;
    }
    /* 移除 handle*/
    foreach($handle as $ch) {
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);
	foreach($data as $key => $json){
		$info = json_decode($json, true);
		print_r($info['data']);
		if(empty($info['errcode'])){
			$arr = explode(".",$info['data']['picName']);
		    $msg = $arr[0].'    '.$info['data']['picUrl']  . PHP_EOL;
	        file_put_contents('success.txt', $msg, FILE_APPEND);
		}
		else{
			$msg = $$json. PHP_EOL;
			file_put_contents('error.txt', $msg, FILE_APPEND);
		}
	}
    //return $data;
}

 

转载于:https://my.oschina.net/u/145255/blog/1817181

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值