View Full Version : Forcing Downloads

08-20-2007, 04:49 PM
Hi guys,

Trying to use PHP to download a pdf from server to local machine.
Got the following:

$bs = Singleton::getInstance('BrowserSniffer');
$file = $_SERVER['DOCUMENT_ROOT'] . '/pdf/' . $location;
$filename = substr(strrchr($file, '/'), 1);
if ($bs->name == 'Mozilla') {
$content_type = "application/octet-stream\n";
$attachment = ' attachment; ';
} else {
$content_type = "application/download\n";
$attachment = ' ';
header('Content-Type: ' . $content_type);
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: ' . $attachment . ' filename=' . $filename);
header('Content-Length: ' . filesize($file));
$fn = fopen($file, 'r');

But cannot get the file to download if $location has spaces. Is there any way around this?


08-20-2007, 06:15 PM
Are you passing file names in the url.

if that is the case, than all non-alphanumeric characters except -_. would be replace with "%"...and as a result, you are referencing a file that does not exist on your system. Therefore, I would strongly recommend that you ensure that the referenced file exists on the file system first, and then force the download.
also, you should use functions such as urldecode (http://www.php.net/manual/en/function.urldecode.php)to remove any encoded file name if you are passing values in the url.

hope that helps.


08-20-2007, 10:54 PM
urlencode($location) should work.

08-21-2007, 08:31 AM
I am getting $location in the function from SQL.
I will try the urlencode anyway.


EDIT: Used the urlencode function on:

header('Content-Disposition: ' . $attachment . ' filename=' . urlencode($filename));

And apart from spaces being transformed to '+' the pdf files download and work.


EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum