Search code examples
phpziparchivephp-ziparchive

Determine archive location with PHP


I am using ZipArchive to zip files but the .zip files are being saved to the home direction http://example.com/. I want them to be saved to http://example.com/downloads/

Here is my code.

<?php
    //Get the directory to zip
    $filename_no_ext= $_GET['loc'];

function recurse_zip($src,&$zip,$path_length) {
        $dir = opendir($src);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    recurse_zip($src . '/' . $file,$zip,$path_length);
                }
                else {
                    $zip->addFile($src . '/' . $file,substr($src . '/' . $file,$path_length));
                }
            }
        }
        closedir($dir);
}
//Call this function with argument = absolute path of file or directory name.
function compress($src) {
        if(substr($src,-1)==='/')
            {
                $src=substr($src,0,-1);
            }
        $arr_src=explode('/',$src);
        $filename=end($arr_src);
        unset($arr_src[count($arr_src)-1]);
        $path_length=strlen(implode('/',$arr_src).'/');
        $f=explode('.',$filename);
        $filename=$f[0];
        $filename=(($filename=='')? 'backup.zip' : $filename.'.zip');

        $zip = new ZipArchive;
        $filename = '/downloads/'.$filename;
        $res = $zip->open($filename, ZipArchive::CREATE);

        if($res !== TRUE)
        {
            echo 'Error: Unable to create zip file';
            exit;
        }
        if(is_file($src))
            {
                $zip->addFile($src,substr($src,$path_length));
            }
        else
        {
            if(!is_dir($src))
            {
                 $zip->close();
                 @unlink($filename);
                 echo 'Error: File not found';
                 exit;
            }
            recurse_zip($src,$zip,$path_length);
        }
        $zip->close();
        header("Location: $filename");
        exit;
}

$zip = compress($_SERVER['DOCUMENT_ROOT'].$_GET['loc'])


        ?>

Solution

  • You kind of have your path as an absolute when I think you were wanting it to be relative.

    try changing '/downloads/' . $filename' to 'downloads/' . $filename.

    OR

    you can do an absolute path like so.

    '/home/path/to/site/downloads/' . $filename

    Specifying the location with a name in $zip->open() with the parameter ZipArchive::CREATE will set the save path