Tuesday, August 18, 2009

How to force open a window that asks to "Open" or "Save As" the file?

Below is the working example of a code that would ask the user to "Open" or "Save" the file.

Note: There should not be any output displayed above the below mentioned code i.e. the rules for "headers" in php applies here.

<?
$contentFilePath = "/docs/xyz.pdf"; // Specify the path to the file that needs to be downloaded. This could also be a file that is generated dynamically.

if ($fd = fopen ($contentFilePath, "rb")) {
$fsize = filesize($contentFilePath);
$fname = basename ($contentFilePath);

// Specify the required headers
header("Pragma: ");
header("Cache-Control: ");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$fname."\"");
header("Content-length: $fsize");

fpassthru($fd);
}
?>

No comments: