Jamol
Jamol

Reputation: 3908

PHP forcing browser to download files (two ways)

I want a php script to download files of any type without opening it. I have found the following functions, which seem to me a bit different, but I don`t know which is better. Please let me know which one is better and reliable:

  1. From PHP Manual

    $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;
    }
    
  2. From other tutorial:

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

Upvotes: 1

Views: 1215

Answers (3)

Vlad
Vlad

Reputation: 795

This is an opinion, but I would use the first one, it's a lot quicker and cleaner.

Upvotes: 0

Xyz
Xyz

Reputation: 6013

They are both basically the same. What you want is the headers

header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"{$file->filename}\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $filesize);
header('Content-Type: image/gif');

And then simply output the file. This can be done in numerous ways, but I would recommend simply:

readfile($filename);

as it is self-explanatory. It will read the file and output it to the output buffer (i.e. the browser).

Note however that the Content-Type header should be set to image/gif if that is what you are outputting.

Upvotes: 1

helderco
helderco

Reputation: 1103

Both are actually pretty similar when you look at the headers that are being sent, which is what forces the download. The difference is in how the file is read. The first one uses readfile() as an abstraction while the second one reads byte per byte.

The second example also uses the @ symbol several times to suppress errors which may not be a good thing to copy.

I'd use the code from the PHP manual. It's simpler, less error-prone, and more readable.

Upvotes: 5

Related Questions