简体   繁体   English

如何在 php 中下载文件

[英]how to download file in php

I want to download image file in 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();
    }
} 

?>

In my index page, I have an anchor tag and if click on anchor tag then above code run.在我的索引页面中,我有一个锚标记,如果单击锚标记,则运行上面的代码。 I am not showing anchor tag because, I put the $filepath static value in above code.我没有显示锚标记,因为我将$filepath static 值放在上面的代码中。 When I run above code then it goes on else condition.当我运行上面的代码时,它会进入其他条件。 I think, full path of project is not taking by above code.我认为,项目的完整路径并没有被上面的代码所采用。 If I put image in same folder then it downloads.如果我将图像放在同一个文件夹中,那么它会下载。

First ensure allow_url_fopen setting in php.ini file is turned on.首先确保php.ini文件中的allow_url_fopen设置已打开。 After that Use this code to download your file:之后使用此代码下载您的文件:

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

For successful download, files directory must be exists.要成功下载,文件目录必须存在。 But I think it would be inefficient to add directory existence check as I think you already know where to save the file you are downloading.但我认为添加目录存在检查效率低下,因为我认为您已经知道在哪里保存正在下载的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM