簡體   English   中英

如何在 php 中下載文件

[英]how to download 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();
    }
} 

?>

在我的索引頁面中,我有一個錨標記,如果單擊錨標記,則運行上面的代碼。 我沒有顯示錨標記,因為我將$filepath static 值放在上面的代碼中。 當我運行上面的代碼時,它會進入其他條件。 我認為,項目的完整路徑並沒有被上面的代碼所采用。 如果我將圖像放在同一個文件夾中,那么它會下載。

首先確保php.ini文件中的allow_url_fopen設置已打開。 之后使用此代碼下載您的文件:

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

要成功下載,文件目錄必須存在。 但我認為添加目錄存在檢查效率低下,因為我認為您已經知道在哪里保存正在下載的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM