How to force file download with PHP

后端 未结 11 1559
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 23:13

I want to require a file to be downloaded upon the user visiting a web page with PHP. I think it has something to do with file_get_contents, but am not sure how

11条回答
  •  攒了一身酷
    2020-11-21 23:25

    The answers above me works. But, I'd like to contribute a method on how to perform it using GET

    on your html/php page

    $File = 'some/dir/file.jpg';
    Download
    

    and download.php contains

    $file = $_GET['f']; 
    
    header("Expires: 0");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $basename = pathinfo($file, PATHINFO_BASENAME);
    
    header("Content-type: application/".$ext);
    header('Content-length: '.filesize($file));
    header("Content-Disposition: attachment; filename=\"$basename\"");
    ob_clean(); 
    flush();
    readfile($file);
    exit;
    

    this should work on any file types. this is not tested using POST, but it could work.

提交回复
热议问题