The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End php download multiple files problem. Reply To: php download multiple files problem.


Guess you’ve been busy.

Yes… you have no idea.

Alright, say you have a download script something like this:


// change as needed.  Users will be allowed to download ALL files in this directory.
define( "DOWNLOAD_DIRECTORY",realpath("./")."/" );

if( isset( $_GET['file'] ) && validate_download_request( DOWNLOAD_DIRECTORY,$_GET['file'] ) ){
    download_file( DOWNLOAD_DIRECTORY,$_GET['file'] );

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>

    var filename = document.querySelector('[data-filename]'),
        download = document.getElementById('dl'),
        url = '',  // 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 );

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.