Reputation: 1591
Want a link that downloads images (*.png, *.jpg, *.gif) to the user's computer.
Tested the following code from the documentation to download a file http://php.net/manual/en/function.readfile.php
index.php
<html>
<head></head>
<body>
<a href="download.php?file=nintendo.png">Download</a>
</body>
</html>
download.php
<?php
$file = $_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "Ingen fil hittades";
}
?>
Have noticed that you can edit the link so you can download everything if you know the file name, even php files.
eg: .../download.php?file=download.php Will download the file download.php
Is it possible to change so that it is only possible to download images? How do I make a secure download of images when the user clicks on a link?
Upvotes: 0
Views: 183
Reputation: 38502
You can simply use the attribute download, which is new to HTML5 and is supported by Firefox and Chrome like this but don't know about IE browsers
<a id="download" href="img/Chrysanthemum.jpg" download="a.jpg">Download</a>
EDIT: to make image simply downloadable, this line is enough.
Content-Disposition: attachment;
Upvotes: 2
Reputation: 503
If you are not limiting what each user can download then I would make life difficult for people to stop them guessing file names. You can try hashing the file name so instead of file=nintendo.png
it would be file=1be98be84d040d99ca85f5a1786821bf7f4fd37a
and your script could then check in the database to find the right file by searching that hash.
This can stop people guessing file names but it cannot stop people working out what your doing, someone might try different hashes such as SHA-1 and MD5 with any file names they currently know and the system would allow them to download the file. In this case it is a good idea to use a salt, that will make the encryption harder to crack.
To use a salt is very simple, when you generate a hash from your file name, you add another variable into the mix, this could be a special password only you know, the date the file was added to your system. Anything that only you will know.
Here is an example;
Current Link: file=nintendo.png
SHA1 Hash: file=1be98be84d040d99ca85f5a1786821bf7f4fd37a
SHA1 Hash + "s3cr3tp4ssw0rd" Salt: file=184649ed65127047f80a46509d0b7447a837b692
You can see that the salt has changed the hash again. I hope this gives you some sort of idea about obfuscating and hashing urls.
Upvotes: 0