How to force file download with PHP

后端 未结 11 1540
被撕碎了的回忆
被撕碎了的回忆 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:18

    In case you have to download a file with a size larger than the allowed memory limit (memory_limit ini setting), which would cause the PHP Fatal error: Allowed memory size of 5242880 bytes exhausted error, you can do this:

    // File to download.
    $file = '/path/to/file';
    
    // Maximum size of chunks (in bytes).
    $maxRead = 1 * 1024 * 1024; // 1MB
    
    // Give a nice name to your download.
    $fileName = 'download_file.txt';
    
    // Open a file in read mode.
    $fh = fopen($file, 'r');
    
    // These headers will force download on browser,
    // and set the custom file name for the download, respectively.
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    
    // Run this until we have read the whole file.
    // feof (eof means "end of file") returns `true` when the handler
    // has reached the end of file.
    while (!feof($fh)) {
        // Read and output the next chunk.
        echo fread($fh, $maxRead);
    
        // Flush the output buffer to free memory.
        ob_flush();
    }
    
    // Exit to make sure not to output anything else.
    exit;
    

提交回复
热议问题