• 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.

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");


5 comments :

  1. Thank you very much for this sir.. it works like charm... thank you again i was looking for this for hour...

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great information. I really thank you for sharing this information to us.
    PHP Training Institute in Chennai
    Dot Net Training And Placement in Chennai
    Core Java Training in Chennai
    Software Testing Training Institute in Chennai

    ReplyDelete