Jump to content

Force download


Jack McKalling

Recommended Posts

I like to write a script that forces the user to download a certain image file, fixed to those imagefiles and no other files. It should pop up the Save As... dialogbox.I prefer javascript on this one, however, if the php script would be understandable and not too long, that would also do it. I am thinking of the IE only "execCommand()" but it should be cross-browser :)Anyone knows something?

Link to comment
Share on other sites

I don't think its possible to make it so that the user gets a "save as" dialogue box for an image in firefox. (with javascript)But after a bit of research, the PHP code is as follows:<?phpheader('Content-type: image/jpeg');header('Content-Disposition: attachment; filename="name.jpg"');?>Save that as...whatever.php, and here's the javascript code:window.location="./whatever.php"And just put a redirect back to the previous page afterwards if a condition is fulfilled. Hope that helps :)Choco

Link to comment
Share on other sites

No that doesn't help. I'll open the downloading file in a new window, so I don't have to use a redirect back. But the downloading file is in another folder than the images (which are actually PNG), so I have to use a path too. And then it doesn't work. The image that would be downloaded has the name inclusive the path, which should be exclusive the path, but then it would not find the file because it is in another folder.Or whatever, I don't understand.Here is the code, I have put in a condition to narrow only PNG files for security.

<?php$file = $_GET["file"];if (!ereg("^\.\.\/art\/.*\.png$",$file)) { die("Access denied, sorry."); }$ffile = substr(htmlentities(urlencode($file)),0,strlen(htmlentities(urlencode($file)))-4);header("Content-type: image/x-png");header("Content-Disposition: attachment; filename=\"{$ffile}\"");?>

(cut off the dot and extension, it got doubled)

Link to comment
Share on other sites

Actually that was necesary for security. I deleted all of it, and reentered it, after I checked php.net, which was a good thing. Now it works :)

<?php$file = $_GET["file"];if (ereg("^\.\.\/art\/.+\.png$",$file)){ $filen = basename($file); header("Content-type: image/x-png"); header("Content-Disposition: attachment; filename={$filen}"); readfile($file);} else{ header("Location: {$_SERVER['HTTP_REFERER']}"); exit();}?>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...