小编hel*_*rco的帖子

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

我想要一个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)

php file download

1
推荐指数
1
解决办法
1195
查看次数

标签 统计

download ×1

file ×1

php ×1