I am creating a php backup script that will dump everything from a database and save it to a file. I have been successful in doing that but now I need to take hundreds of images in a directory and compress them into one simple .tar.gz file.
What is the best way to do this and how is it done? I have no idea where to start.
Thanks in advance
If you are using PHP 5.2 or later, you could use the Zip Library
and then do something along the lines of:
$images_dir = '/path/to/images';
//this folder must be writeable by the server
$backup = '/path/to/backup';
$zip_file = $backup.'/backup.zip';
if ($handle = opendir($images_dir))
{
$zip = new ZipArchive();
if ($zip->open($zip_file, ZipArchive::CREATE)!==TRUE)
{
exit("cannot open <$zip_file>\n");
}
while (false !== ($file = readdir($handle)))
{
$zip->addFile($images_dir.'/'.$file);
echo "$file\n";
}
closedir($handle);
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
echo 'Zip File:'.$zip_file . "\n";
}
$archive_name = 'path\to\archive\arch1.tar';
$dir_path = 'path\to\dir';
$archive = new PharData($archive_name);
$archive->buildFromDirectory($dir_path); // make path\to\archive\arch1.tar
$archive->compress(Phar::GZ); // make path\to\archive\arch1.tar.gz
unlink($archive_name); // deleting path\to\archive\arch1.tar
You can also use something like this:
exec('tar -czf backup.tar.gz /path/to/dir-to-be-backed-up/');
Be sure to heed the warnings about using PHP's exec()
function.
My simple 2 lines PHP file by which I can create a backup ZIP file within a few seconds:
Just browse: http://mysiteurl.com/create-my-zip.php
<?php
/* PHP FILE NAME: create-my-zip.php */
echo exec('tar zcf my-backup.tar.gz mydirectory/*');
echo '...Done...';
?>
Simply upload this file into the server and browse directly.
Notes:
- 'mydirectory' ==> target directory relative to this PHP script;
- 'my-backup.tar.gz' ==> will be created at the same directory where this PHP file is uploaded;
You can easily gzip a folder using this command:
tar -cvzpf backup.tar.gz /path/to/folder
This command can be ran through phps system()-function.
Don't forget to escapeshellarg() all commands.
Chosen answer doesn't support recursion (subdirectories), so here you go:
<?
ignore_user_abort(true);
set_time_limit(3600);
$main_path = 'folder2zip';
$zip_file = 'zipped.zip';
if (file_exists($main_path) && is_dir($main_path))
{
$zip = new ZipArchive();
if (file_exists($zip_file)) {
unlink($zip_file); // truncate ZIP
}
if ($zip->open($zip_file, ZIPARCHIVE::CREATE)!==TRUE) {
die("cannot open <$zip_file>\n");
}
$files = 0;
$paths = array($main_path);
while (list(, $path) = each($paths))
{
foreach (glob($path.'/*') as $p)
{
if (is_dir($p)) {
$paths[] = $p;
} else {
$zip->addFile($p);
$files++;
echo $p."<br>\n";
}
}
}
echo 'Total files: '.$files;
$zip->close();
}