Note Submitter: Alcator
----
I thought I'd share this nifty little code that works with headers.
In many situations, you may be asked to obfuscate actual downloadable files location, or perhaps only allow logged users to download a file.
In this example, I'm offering alternate download link for those who use old Internet Explorer; feel free to remove the whole alternate part as needed.
This is translated fragment of actual used code.
<?php
echo '<a href="./provide_file.php?file='.$id.'relid='.$url.'">Direct download link</a>'. // COMMENT: call provide_file.php with ID of the file and relation identifier (relid) that is used to authenticate user.
//output continues here:
'<br /><br />
If your browser doesn't offer you the file for saving, please try the following link instead:
'.(IsSet($_REQUEST['dl'])?'<a href="'.$FileRecord['filename'].'">DOWNLOAD FILE</a>':
'<a href="./?mat='.$id.'&dl=1">Go to download</a>'); // the trick with "dl" parameter allows us to count number of downloads (we store that into database when dl is present in the URL).
?>
Now, what does provide_file.php do?
First, we have to somehow get the filename:
$query1 = "select filename from files where file_id = ".intval($_REQUEST['file']);
(call mysql_query($query1) to make this query. If it fails or finds zero entries, abort execution (die(1);) )
If a record is found (and eventually the user is authenticated using the relid string), the following sequence will prompt the user to download the file:
<?php
$res = mysql_fetch_row($q); // Get the record from DB.
$tmp1 = $res[0]; // the following sequence extracts the filename from the complete path stored in filename column:
while (strpos($tmp1,"/")!==false) // originally, $tmp1 is something like /files/filename.zip; while there are slashes, cut the first char:
{
$tmp1 = substr($tmp1,1); // cut the first char.
}
Header ("Content-type: application/x-zip-compressed"); // assuming the file is zip
header('Content-Disposition: attachment; filename="'.$tmp1.'"'); // This ensures prompt "What do you want to do with the file", with "Save to disk" preferred.
$tmp = file_get_contents($res[0]); // read the contents of the file into a variable...
echo $tmp; // ... and output it after the headers.
?>
If you have multiple options of file types, you need to store the type or extract it from the filename (substr($filename,-3) gives you the extension); this can also be used for images if you want to block hotlinking - just set: src="provide_image.php?..." which works similarly and has Content-Type: image/gif or image/png or image/jpg as content type; in the case of images, don't use Content-disposition header; just read the file and echo it.
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.