Avoid absolute path names for zip file contents

I am writing in php. I have the following code:

$folder_to_zip = "/var/www/html/zip/folder";
$zip_file_location = "/var/www/html/zip/archive.zip";
$exec = "zip -r $zip_file_location  '$folder_to_zip'";

exec($exec);

I would like to have a zip file stored in /var/www/html/zip/archive.zipwhich it does, but when I open this zip file, the whole server path is inside the zip file. How to write this so that the server path was NOT inside the zip file?

the script executing this command is not in the same directory. It is located in/var/www/html/zipfolder.php

+3
source share
2 answers

zip seeks to store files in any way that was provided to it for access to them. Greg's comment gives you a potential fix for your particular directory tree. More generally, you could - a little rudely - do something like this

$exec = "cd '$folder_to_zip' ; zip -r '$zip_file_location  *'"

, , ( , , - ), , -

$exec = "cd '$parent_of_folder' ; zip -r '$zip_file_location $desired_folder'"

: ,

+5

, PHP, Windows Linux.

function Zip($source, $destination, $include_dir = false)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = realpath($source);

    if (is_dir($source) === true)
    {

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        if ($include_dir) {

            $arr = explode(DIRECTORY_SEPARATOR, $source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) {
                $source .= DIRECTORY_SEPARATOR . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        foreach ($files as $file)
        {
            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . DIRECTORY_SEPARATOR, '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}
+1

All Articles