Home › Forums › Back End › php download multiple files problem. › Reply To: php download multiple files problem.
September 26, 2014 at 4:25 pm
#184821
Participant
Guess you’ve been busy.
Yes… you have no idea.
Alright, say you have a download script something like this:
<?php
// change as needed. Users will be allowed to download ALL files in this directory.
// KEEP TRAILING SLASH.
define( "DOWNLOAD_DIRECTORY",realpath("./")."/" );
if( isset( $_GET['file'] ) && validate_download_request( DOWNLOAD_DIRECTORY,$_GET['file'] ) ){
download_file( DOWNLOAD_DIRECTORY,$_GET['file'] );
exit;
}
function validate_download_request( $dir,$file ){
return (realpath( $dir.$file ) === $dir.$file);
}
function download_file( $dir,$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( $dir.$file ) );
readfile( $dir.$file );
}
Your download page (w/ JS) would look something like this:
<!doctype html>
<!-- etc. . . . -->
<input data-filename>
<button id=dl>download file</button>
<script>
(function(){
var filename = document.querySelector('[data-filename]'),
download = document.getElementById('dl'),
url = 'http://example.com/download.php', // change as needed
dl_onClick = function( event ){
var dltarget = document.createElement('iframe');
dltarget.src = url+"?file="+encodeURIComponent( filename.value );
dltarget.setAttribute( 'style',"visibility:hidden;display:none;" );
document.body.appendChild( dltarget );
};
download.addEventListener( 'click',dl_onClick );
})()
</script>
That’s it. When you click the button, javascript takes the value in the input and uses it to create an iframe which passes it to your php script. The php script checks if the file exists in the download directory, and serves it if so.
tested.