Hello,
I have a small Issue with a download script. The links I generate based upon a section of my file system, call a download.php script to determine how to serve the files, which are located outside of my web tree.
If a user issues a "Save as" on the link, the file to be saved will be download.php or download.ext (ext based on mime definition) if it is of a special MIME type that I have declared handeling for (i.e. a txt file, word document etc.). If the file extension is unknown to my handler code, such as file.conf, a "Save as" will download with the correct file name. Is there a way I can determine how the user issued the request to get the file? Either from a direct link, or save as? Any suggestions here are appreciated. Note that when the user simply clicks the link, the files will load inside the browser correctly. I'm just going for a best of both worlds...
The Download Script:
<?php
define('FILEDIR', '/Tree_Path/');
if (isset($_GET[file]) )
$file=$_GET['file'];
elseif (isset($_POST['file']) )
$file=$_POST['file'];
$path = FILEDIR . $file;
//echo $path;
if (!is_file($path))
{
header("Location: filegeterror.php?error=1");
exit();
}
/*
** //TO BE ADDED check that the user has permission to download file
** if(user does not have permission)
** {
** //redirect to error page
** header("Location: .php");
** exit();
** }
*/
$mimetype = array(
'doc'=>'application/msword',
'htm'=>'text/html',
'html'=>'text/html',
'jpg'=>'image/jpeg',
'pdf'=>'application/pdf',
'txt'=>'text/plain',
'xls'=>'application/vnd.ms-excel'
);
$p = explode('.', $file);
$pc = count($p);
//send headers
if(($pc > 1) AND isset($mimetype[$p[$pc - 1]]))
{
//display file inside browser
header("Content-type: " . $mimetype[$p[$pc - 1]] . "\n");
}
else
{
//force download dialog
header("Content-type: application/octet-stream\n");
header("Content-disposition: attachment; filename=\"$file\"\n");
}
header("Content-transfer-encoding: binary\n");
header("Content-length: " . filesize($path) . "\n");
//send file contents
$fp=fopen($path, "r");
fpassthru($fp);
?>
Sample Script to Generate Links based upon the filesystem:
<?php
define('FILEDIR', '/Tree_Path/');
//display available files
$d = dir(FILEDIR);
while($f = $d->read())
{
//skip 'hidden' files
if($f{0} != '.')
{
print("<a href=\"download.php?file=$f\">$f</a><br>\n");
}
}
$d->close();
?>