Safari and application/octet-stream issue

matthew016
matthew016 used Ask the Experts™
on
Hi,

When a user clicks an some link called "export", a .csv file is generated.

The code is the following:

header("Content-type: application/octet-stream; charset=utf-8");
header("Content-Disposition: attachment; filename=\"export-" . date('Y-m-d-H-i-s') . ".csv\"");
$s = "some data";
echo $s;

In Chrome and Mozilla when I click on this link, the .csv file is saved on my computer.
However, in Safari, it suggests me to save a .csv.html file, which is not so convenient for the user.

Thank you for any help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016
Commented:
This is how I force a download.  Maybe if you adapt this header set it will work for your needs.  Please let me know if you have any questions.  Best, ~Ray
<?php // RAY_force_download.php
error_reporting(E_ALL);


// A FILE TO DOWNLOAD - THIS LINK COULD COME IN THE URL VIA $_GET OR COULD BE GENERATED INSIDE THE SCRIPT
$url = "http://a0.twimg.com/a/1252097501/images/twitter_logo_header.png";


// USE CASE
force_download($url);


// FUNCTION TO FORCE A DOWNLOAD
function force_download($filename)
{
   $basename = basename($filename);
   $filedata = file_get_contents($filename);

   if ($filedata)
   {
   // THESE HEADERS ARE USED ON ALL BROWSERS
      header("Content-Type: application-x/force-download");
      header("Content-Disposition: attachment; filename=\"$basename\"");
      header("Content-length: ".(string)(strlen($filedata)));
      header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
      header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

   // THIS HEADER MUST BE OMITTED FOR IE 6+
      if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
      {
         header("Cache-Control: no-cache, must-revalidate");
      }

   // THIS IS THE LAST HEADER
      header("Pragma: no-cache");

   // FLUSH THE HEADERS TO THE BROWSER
      flush();

   // CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
      ob_start();
      echo $filedata;
   }
}

Open in new window

Author

Commented:
I've found out I was outputting an exception also, and that this caused it.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Thanks for the points - yea, that would do it - you have to send all of your headers before any browser output.  Often there is a problem that arises from whitespace or an error message.  Best, ~Ray

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial