Search code examples
phpzipphp-ziparchive

Don't want directory structure with ZipArchive


I am trying to make file download script that collection all the files and download a zip file that has that collection of files not all the directory structure..

i have the file in download/folder1/folder1/filename.extension

here is my PHP codes:

if( !extension_loaded('zip') ){
    echo "<script>alert('Error: Please contact to the Server Administrator!');</script>";
    exit;
}

$zip = new ZipArchive;
if( $zip->open($zipname, ZipArchive::OVERWRITE) === TRUE ){
    foreach( $files as $file ){
        $zip->addFile( BASE_PATH.$file_path.'/'.$file, $file );
    }
    $zip->close();
} else {
    echo "<script>alert('Error: problem to create zip file!');</script>";
    exit;
}

this code gives me the structure like this:

enter image description here

it gives the complete path of wamp(including the path director and files) and the files, i just want to add the files not the directory..

Can someone tell me what i missed??


Solution

  • Every time download link comes with the unique download key, i just add the unique_key with the name of download.zip file and its working...

    // $db_secret_key Random Unique Number
    $zipname = $db_secret_key."_download.zip";
    
    if( !extension_loaded('zip') ){
         echo "<script>alert('Error: Please contact to the Server Administrator!');</script>";
         exit;
    }
    
    
    $zip = new ZipArchive;
    if( $zip->open($zipname, ZipArchive::CREATE) === TRUE ){
         foreach( $files as $file ){
               $zip->addFile( BASE_PATH.$file_path.'/'.$file, $file );
         }
         $zip->close();
    
         // Force Download
         header("Content-Type: application/zip");
         header("Content-disposition: attachment; filename=$zipname");
         header("Content-Length: ".filesize($zipname)."");
         header("Pragma: no-cache");
         header("Expires: 0");
         readfile($zipname);
         exit;
    } else {
         echo "<script>alert('Error: problem to create zip file!');</script>";
         exit;
    }