【问题标题】:PHP File Down with header()PHP File Down 与 header()
【发布时间】:2017-02-06 07:30:33
【问题描述】:

我编写了以下代码以允许在不显示源的情况下下载文件。

在本例中,文件“test.pdf”已下载,但已损坏。

谁能看出会出现这种情况的任何原因?

$path = 'http://www.domain.org/images/uploads/test.pdf';

// Directory Path
$directory_path_filename = str_replace('http://www.domain.org/', '', $path);

$filepath = '/var/sites/l/domain.org/public_html/'.$directory_path_filename;

if ( file_exists( $filepath ) ) {

    $finfo = finfo_open( FILEINFO_MIME );
    header( 'Content-Type: application/pdf' );
    header( 'Content-Disposition: attachment; filename= ' . basename( $filepath ) );
    header( 'Content-Length: ' . filesize( $filepath ) );
    header( 'Expires: 0' );
    finfo_close( $finfo );

    ob_clean( );
    flush( );
    readfile( $filepath );
    exit;
}

【问题讨论】:

    标签: php header content-type mime


    【解决方案1】:

    请使用此方法

    $file 接收完整路径,$filename 是下载文件名。

    public static function downloadFile($file, $filename)
        {
            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename = '.basename($filename));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check = 0, pre-check = 0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                die;
            }
        }
    

    【讨论】:

    • 嗨佩德罗。谢谢,但这仍然会导致同样的问题。文件下载后无法打开。
    • 在这种情况下,您可能在标题之前有一些输出......比如一个noite或其他东西,您能发布完整的代码吗?
    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2019-05-22
    • 2019-09-12
    • 1970-01-01
    • 2012-08-06
    • 2022-12-02
    相关资源
    最近更新 更多