PHP强制浏览器下载文件(两种方式)

Jam*_*mol 1 php file download

我想要一个PHP脚本来下载任何类型的文件而无需打开它.我发现了以下功能,在我看来有点不同,但我不知道哪个更好.请让我知道哪一个更好,更可靠:

  1. PHP手册

    $file = 'monkey.gif';
    
    if (file_exists($file)) {
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename='.basename($file));
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file));
      ob_clean();
      flush();
      readfile($file);
      exit;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 从其他教程:

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=\"{$file->filename}\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $filesize);
    
    // download
    // @readfile($file_path);
    $dwn_file = @fopen($file_path,"rb");
    if ($dwn_file) {
      while(!feof($dwn_file)) {
        print(fread($dwn_file, 1024*8));
        flush();
        if (connection_status()!=0) {
          @fclose($dwn_file);
          die();
        }
      }
      @fclose($dwn_file);
    }
    
    Run Code Online (Sandbox Code Playgroud)

hel*_*rco 5

当您查看正在发送的标头时,两者实际上非常相似,这是强制下载的原因.不同之处在于文件的读取方式.第一个readfile()用作抽象,而第二个用于每字节读取字节.

第二个例子也@多次使用符号来抑制错误,这些错误可能不是一件好事.

我将使用PHP手册中的代码.它更简单,更不容易出错,而且更具可读性.