繁体   English   中英

PHP File Down与header()

[英]PHP File Down with header()

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

在此示例中,文件“ 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;
}

请使用此方法

$ 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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM