Commit 1d22a338 authored by jiangkebao's avatar jiangkebao
Browse files

下载远程文件

parent f68443a3
Loading
Loading
Loading
Loading
+36 −0
Original line number Diff line number Diff line
@@ -814,3 +814,39 @@ if (!function_exists('get_images_url')) {
        return $match;
    }
}


if (!function_exists('download_file')) {
    /**
     * 下载远程文件
     * @param $url 远程文件路径
     * @param null $path 系统保存路径
     * @return string
     */
    function download_file($url, $path = null)
    {
        $filename = trim(pathinfo($url, PATHINFO_FILENAME));
        $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
        $filename = "$filename.$ext";
        $root = config('server.settings.document_root', BASE_PATH . '/public');
        $path = $path ? $path : '/download/files';
        $savePath = $root . $path;
        if (!is_dir($savePath)) {
            // 判断路径是否存在,不存在,则创建
            mkdir($savePath, 0777, true);
        }
        $filePath = $savePath . '/' . $filename;
        if (!file_exists($filePath)) {
            $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);
            $resource = fopen($filePath, 'a');
            fwrite($resource, $file);
            fclose($resource);
        }
        return $path . '/' . $filename;;
    }
}
 No newline at end of file