php 多线程批量下载图片
作者:钓赛通
发布时间:2024-08-22
点击数:
// 多线程下载图片 public function downloadImages($imgarr) { try { $mh = curl_multi_init(); $handles = []; foreach ($imgarr as $i => $itemss) { $ch = curl_init(); $filename = $itemss['local_save_path']; $fp = fopen($filename, 'w'); curl_setopt($ch, CURLOPT_URL, $itemss['res_url']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_REFERER, $itemss['res_url']); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $handles[$i] = ['ch' => $ch, 'fp' => $fp]; curl_multi_add_handle($mh, $ch); } $running = null; do { curl_multi_exec($mh, $running); } while ($running > 0); foreach ($handles as $handle) { curl_multi_remove_handle($mh, $handle['ch']); curl_close($handle['ch']); fclose($handle['fp']); } curl_multi_close($mh); } catch (\Error $error) { } catch (\Exception $exception) { } } $imgarr = [ [ 'local_save_path' => '', //本地保存路径 'res_url' => '', //网络图片链接 ] ];