美文网首页
php 远程下载文件保存到本地服务器的指定目录 2022-1

php 远程下载文件保存到本地服务器的指定目录 2022-1

作者: 阿然学编程 | 来源:发表于2022-11-22 15:13 被阅读0次
    • 保存到服务器中
    /**
     * @param $url  远程地址:"http://www.baidu.com/img/baidu_jgylogo3.gif"
     * @param $path 本地保存目录:/www/wwwroot/dow/
     * @return bool
     */
    function download_file($url, $path)
    {
        // 检查路径是否存在,如果不存在则创建
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    
        // 解码URL中的文件名
        $decoded_file = urldecode(basename($url));
    
        // 拼接文件路径
        $file_path = $path . mb_convert_encoding($decoded_file, "GB2312", "UTF-8");
    
        // 初始化 curl 会话
        $ch = curl_init();
    
        // 设置要请求的 URL
        curl_setopt($ch, CURLOPT_URL, $url);
    
        // 设置请求超时时间(单位:秒)
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    
        // 设置输出文件流
        curl_setopt($ch, CURLOPT_FILE, fopen($file_path, 'w+'));
    
        // 开启重定向跟踪功能
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
        // 执行 curl 请求
        $result = curl_exec($ch);
    
        // 获取 HTTP 状态码
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
        // 关闭 curl 会话
        curl_close($ch);
    
        // 如果请求失败或HTTP状态码不是200,删除该文件并返回false
        if ($result === false || $httpcode !== 200) {
            unlink($file_path);
            return false;
        }
    
        // 返回true表示下载成功
        return true;
    }
    

    相关文章

      网友评论

          本文标题:php 远程下载文件保存到本地服务器的指定目录 2022-1

          本文链接:https://www.haomeiwen.com/subject/ibooxdtx.html