使用curl的多線程,另外curl可以設置請求時間,遇到很慢的url資源,可以果斷的放棄,這樣沒有阻塞,另外有多線程請求,效率應該比較高
下面是代碼實現:
- /**
- * curl 多線程
- * @author http://www.lai18.com
- * @param array $array 並行網址
- * @param int $timeout 超時時間
- * @return mix
- */
- public function Curl_http($array,$timeout='15'){
- $res = array();
- $mh = curl_multi_init();//創建多個curl語柄
- foreach($array as $k=>$url){
- $conn[$k]=curl_init($url);//初始化
- curl_setopt($conn[$k], CURLOPT_TIMEOUT, $timeout);//設置超時時間
- curl_setopt($conn[$k], CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
- curl_setopt($conn[$k], CURLOPT_MAXREDIRS, 7);//HTTp定向級別 ,7最高
- curl_setopt($conn[$k], CURLOPT_HEADER, false);//這裡不要header,加塊效率
- curl_setopt($conn[$k], CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
- curl_setopt($conn[$k], CURLOPT_RETURNTRANSFER,1);//要求結果為字符串且輸出到屏幕上
- curl_setopt($conn[$k], CURLOPT_HTTPGET, true);
- curl_multi_add_handle ($mh,$conn[$k]);
- }
- //防止死循環耗死cpu 這段是根據網上的寫法
- do {
- $mrc = curl_multi_exec($mh,$active);//當無數據,active=true
- } while ($mrc == CURLM_CALL_MULTI_PERFORM);//當正在接受數據時
- while ($active and $mrc == CURLM_OK) {//當無數據時或請求暫停時,active=true
- if (curl_multi_select($mh) != -1) {
- do {
- $mrc = curl_multi_exec($mh, $active);
- } while ($mrc == CURLM_CALL_MULTI_PERFORM);
- }
- }
- foreach ($array as $k => $url) {
- if(!curl_errno($conn[$k])){
- $data[$k]=curl_multi_getcontent($conn[$k]);//數據轉換為array
- $header[$k]=curl_getinfo($conn[$k]);//返回http頭信息
- curl_close($conn[$k]);//關閉語柄
- curl_multi_remove_handle($mh , $conn[$k]); //釋放資源
- }else{
- unset($k,$url);
- }
- }
- curl_multi_close($mh);
- return $data;
- }
- //參數接收
- $callback = $_GET['callback'];
- $hrefs = $_GET['hrefs'];
- $urlarray = explode(',',trim($hrefs,','));
- $date = date('Ymd',time());
- //實例化
- $img = new HttpImg();
- $stime = $img->getMicrotime();//開始時間
- $data = $img->Curl_http($urlarray,'20');//列表數據
- mkdir('./img/'.$date,0777);
- foreach ((array)$data as $k=>$v){
- preg_match_all("/(href|src)=(["|']?)([^ "'>]+.(jpg|png|PNG|JPG|gif))\2/i", $v, $matches[$k]);
- if(count($matches[$k][3])>0){
- $dataimg = $img->Curl_http($matches[$k][3],'20');//全部圖片數據二進制
- $j = 0;
- foreach ((array)$dataimg as $kk=>$vv){
- if($vv !=''){
- $rand = rand(1000,9999);
- $basename = time()."_".$rand.".".jpg;//保存為jpg格式的文件
- $fname = './img/'.$date."/"."$basename";
- file_put_contents($fname, $vv);
- $j++;
- echo "創建第".$j."張圖片"."$fname"."<br/>";
- }else{
- unset($kk,$vv);
- }
- }
- }else{
- unset($matches);
- }
- }
- $etime = $img->getMicrotime();//結束時間
- echo "用時".($etime-$stime)."秒";
- exit;