Chozo4 Posted August 26, 2007 Share Posted August 26, 2007 (edited) Ripken has the idea but he's mixing the idea of php with javascript. You cannot call a php (serverside) function directly from html or javascript (clientside).Download.php<? //NOTE: I took the liberty to make it a slight bit more secure. //By preventing outsiders from downloading anything they want //through adding a path to any other folder on your webserver //or even worse abusing it to use the page as an http-proxy. //Collect the passed filename from $_GET['file'] and then //strip out any paths to avoid the client from downloading //anything they want from outside the directory this script is in. $file=preg_replace('#.*[/\\\]#','',$_GET['file']); //Insert here the path to your files folder or leave empty for //script-root. For example: $path='myfiles/folder/is/here/'; $path=''; //check if the file exists - if not then stop executing if(!file_exists("$path$file")) die('File does not exist'); //send the neccessary headers since the file clears as existing header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename=$file'); //Read the file in and send readfile($file);?>We would then call the script from the client (your html webpage or whatnot) by using this:<a href='download.php?file=whateverfile.pdf'>As mentioned nothing needs to be on the page for the header parts to work but that means that no output can be sent before calling them in the php script itself (code is fine without output). It doesnt matter what page is already loaded but rather what's sent from the script. Also, I could have hardened the code more to only accept PDF extensions but I didn't want to make it too much to handle. Edited August 26, 2007 by Chozo4 Link to comment Share on other sites More sharing options...
ripken204 Posted August 26, 2007 Share Posted August 26, 2007 (edited) crap ur right, the way i do that type of stuff is that i have a process.php file where any processes such as dloading or logging in would take place, just so that i dont have 20 different files for each process.<a href='process.php?action=download&file=whateverfile.pdf'>so i would have to call it like that then use your scriptthen this is how the process.php file would look:<? if($_GET['action']=='download'){ $file=preg_replace('#.*[/\\\]#','',$_GET['file']); $path=''; if(!file_exists("$path$file")) die('File does not exist'); header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename=$file'); readfile($file); }?> Edited August 26, 2007 by ripken204 Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now