首页 > 解决方案 > 如何在php中下载文件

问题描述

我想在 php 中下载图像文件。

<?php
if(isset($_REQUEST["file"])){

    $filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png';

    // Process download
    if(file_exists($filepath)) {
        echo $filepath;
        exit;
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        die();
    } else {
        echo $filepath;
        exit;
        http_response_code(404);
        die();
    }
} 

?>

在我的索引页面中,我有一个锚标记,如果单击锚标记,则运行上面的代码。我没有显示锚标记,因为我将$filepath静态值放在上面的代码中。当我运行上面的代码时,它会进入其他条件。我认为,项目的完整路径并没有被上面的代码所采用。如果我将图像放在同一个文件夹中,那么它会下载。

标签: phpdownload

解决方案


首先确保打开文件中的allow_url_fopen设置。php.ini之后使用此代码下载您的文件:

<?php
    $url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
    $file = './files/'.basename($url);
    file_put_contents($file, file_get_contents($url));
?>

要成功下载,文件目录必须存在。但我认为添加目录存在检查效率低下,因为我认为您已经知道在哪里保存正在下载的文件。


推荐阅读