Detailed explanation of sample code for php to download files to local area

黄舟
Release: 2023-03-06 15:56:01
Original
1588 people have browsed it

Note: This demo is suitable for the yii framework. If you are not using the yii framework, this method is also applicable to you. Just understand the idea briefly

   /**
     * 保存文件到本地
     * @param 文件路径 $url
     * @param 保存本地路径 $savePath
     * @return string
     */
    public static function downloadFile($url) {
        $www_root = Yii::getPathOfAlias('webroot');
        $root_dir = 'uploads/audio';
        $build_dir = date('Y') . '/' . date('m');
        $origin_dir = $root_dir . '/' . $build_dir;
        $savePath = $www_root . DIRECTORY_SEPARATOR . $origin_dir . DIRECTORY_SEPARATOR;// 本地存放的路径(我是按照年月日来划分)
        $fileName = Common::getUrlFileExt($url);                                     // 获取文件扩展名
        if (!file_exists($savePath)) {
            Common::mkdirs($savePath);                                              //目录不存在创建目录
        }
        $fileName = time() . '.' . $fileName;
        //$file = file_get_contents($url);
        $ch = curl_init();
        $timeout = 60;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);                                                //使用curl $ch 为返回的文件流
        if (!empty($file_contents)) {
            file_put_contents($savePath . '/' . $fileName, $file_contents);  //保存到本地的地址
            return '/' . $origin_dir . '/' . $fileName;                  //返回本地地址
        }
    }

    /**
     * 获取文件扩展名
     * @param 网页URL $url
     * @return string
     */
    public static function getUrlFileExt($url) {
        $ary = parse_url($url);
        $file = basename($ary['path']);
        $ext = explode('.', $file);
        return $ext[1];
    }
Copy after login
    /**
     * 创建多级目录
     */
    public static function mkdirs($dir) {
        if (!is_dir($dir)) {
            if (!Common::mkdirs(dirname($dir))) {
                return false;
            }
            if (!mkdir($dir, 0777)) {
                return false;
            }
        }
        return true;
    }
Copy after login
downloadFile(http://www.php.cn/);  // 调用
Copy after login

The above is the detailed content of Detailed explanation of sample code for php to download files to local area. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template