• My PHP Pages

    This is a complete and free PHP programming course for beginners. Everything you need to get started is set out in section one below.

Showing posts with label PHP ZIP Folders. Show all posts
Showing posts with label PHP ZIP Folders. Show all posts

Sep 22, 2013

Posted by Unknown
5 comments | 11:32 PM

                                                      You can use PHP ZIP function to make archives using PHP. I have create a PHP Class to zip all folders and files in a given directory you just need to add source directory and  destination path. Look at the code bellow... Copy bellow code and save it as PHP file name it as 'tozip.class.php'





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

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

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $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 . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}



Use Bellow Code to execute the function where you need. You need to include 'tozip.class.php' file too


require_once('tozip.class.php');
zip("your_source_path","your_destination_path/your_file_name.zip");


Read More..