views:

41

answers:

2

I have a function for outputting documents, images etc:

public function direct($theMimeType, $thePath)
{
    header('Content-type: '.$theMimeType);
    ob_clean(); // clean output buffer
    flush(); // flush output buffer 
    readfile($thePath);
    exit;
}

It works great in Firefox. The file opens whether it is PDF, DOCX or any other file. However, in IE it freezes and nothing shows up.

What could cause this?

EDIT:

I have added few other headers:

public function direct($theMimeType, $thePath)
{
    $aSize = filesize($thePath);
    $aBegin = 0;
    $aEnd = $aSize;
    $aFilename = end(explode('/', $thePath));   
    $aTime = date('r', filemtime($thePath));
    $aContentDisposition = ('application/pdf' === $theMimeType) ? 'inline' : 'atachment';
    header('HTTP/1.0 200 OK'); 
    header("Content-Type: $theMimeType");
    header('Cache-Control: public, must-revalidate, max-age=0');
    header('Pragma: no-cache'); 
    header('Accept-Ranges: bytes');
    header('Content-Length:'.($aEnd-$aBegin));
    header("Content-Range: bytes $aBegin-$aEnd/$aSize");
    header("Content-Disposition: $aContentDisposition; filename=$aFilename");
    header("Content-Transfer-Encoding: binary\n");
    header("Last-Modified: $aTime");
    header('Connection: close');
    ob_clean(); // clean output buffer
    flush(); // flush output buffer 
    readfile($thePath);
    exit;
}

Well, it works in IE now but still it opens the file much slower than Firefox. There seems to be few seconds freeze up before the IE browser opens the file.

+1  A: 
  • Make this file download directly, not using any scripts
  • make sure it works in IE
  • in firefox, use LiveHTTPHeaders to watch what headers being sent by web-server
  • in firefox, use LiveHTTPHeaders to watch what headers being sent by your script
  • make your script's headers the same as web-server's
Col. Shrapnel
Well, I cannot download this file directly as it is outside of web accessible document root.
Richard Knop
@Richard please read whole answer, not first line only
Col. Shrapnel
+1  A: 

Most of those headers aren't really necessary. I prefer to keep things simple:

header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public');
header ('Content-Type: '.$theMimeType);
header ('Content-Disposition: '.$aContentDisposition.'; filename="'.$aFilename.'"');
header ('Content-Transfer-Encoding: binary');
header ('Content-Length: '.$aSize);

Watch out for the \n at the end of your Content-Transfer-Encoding header.

The 'Pragma: public' is a workround specifically to handle a problem with IE and https connections. The other key difference is $aFilename in quotes.

Mark Baker
Yeah, filename without quotes' probably been confusing Internet Explorer.
Richard Knop