最近用的经常使用到远程下载文件的函数,省得每次搜索,记录一下备用
方法一:
function download($url, $path = 'images/') { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $file = curl_exec($ch); curl_close($ch); if($file==false){ exit('无法下载!'); } $filename = pathinfo($url, PATHINFO_BASENAME); $resource = fopen($path . $filename, 'a'); fwrite($resource, $file); fclose($resource); }
方法二:
// 应用目录为当前目录 define('APP_PATH', __DIR__ . '/'); //获取下载链接 $remote_url = $_GET['url']; if(strpos($remote_url,'http')===false){ exit('链接错误!'); } //取文件后缀名并拼接新文件 $dix = explode('.',$remote_url); $filename = date('YmdHis').'.'.end($dix); $tmp_path = APP_PATH.'public/'.$filename; try { set_time_limit(0); touch($tmp_path); // 做些日志处理 if ($fp = fopen($remote_url, "rb")) { if (!$download_fp = fopen($tmp_path, "wb")) { exit('无法打开链接!'); } while (!feof($fp)) { if (!file_exists($tmp_path)) { // 如果临时文件被删除就取消下载 fclose($download_fp); exit('临时文件被删除'); } fwrite($download_fp, fread($fp, 1024 * 8 ), 1024 * 8); } fclose($download_fp); fclose($fp); } else { exit('无法下载'); } } catch (Exception $e) { Storage::remove($tmp_path); exit('发生错误:'.$e->getMessage()); }