try to download file and getting invalid file in response in core php

后端 未结 3 1851
孤独总比滥情好
孤独总比滥情好 2021-01-28 09:00

I download a file but it gives invalid file in return.

Here\'s my download_content.php



        
3条回答
  •  长发绾君心
    2021-01-28 09:50

    As said in the other question, this way looks better:

    $filename = $_GET["filename"];
    // Validate the filename (You so don't want people to be able to download
    // EVERYTHING from your site...)
    
    // For example let's say that you hold all your files in a "download" directory
    // in your website root, with an .htaccess to deny direct download of files.
    // Then:
    
    $filename = './download' . ($basename = basename($filename));
    
    if (!file_exists($filename))
    {
        header('HTTP/1.0 404 Not Found');
        die();
    }
    // A check of filemtime and IMS/304 management would be good here
    // Google 'If-Modified-Since', 'If-None-Match', 'ETag' with 'PHP'
    
    // Be sure to disable buffer management if needed
    while (ob_get_level()) {
       ob_end_clean();
    }
    
    Header('Content-Type: application/download');
    Header("Content-Disposition: attachment; filename=\"{$basename}\"");
    header('Content-Transfer-Encoding: binary'); // Not really needed
    Header('Content-Length: ' . filesize($filename));
    Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    
    readfile($filename);
    

    That said, what does "invalid file" mean? Bad length? Zero length? Bad file name? Wrong MIME type? Wrong file contents? The meaning may be clear to you with everything under your eyes, but from our end it's far from obvious.

    UPDATE: apparently the file is not found, which means that the filename= parameter to the PHP script is wrong (refers a file that's not there). Modified the code above to allow a directory to contain all files, and downloading from there.

提交回复
热议问题