Php backup all files

menzerath / backup.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/*
* PHP: Recursively Backup Files & Folders to ZIP-File
* MIT-License — 2012-2018 Marvin Menzerath
*/
// Make sure the script can handle large folders/files
ini_set( ‘max_execution_time’ , 600 );
ini_set( ‘memory_limit’ , ‘1024M’ );
// Start the backup!
zipData( ‘/path/to/folder’ , ‘/path/to/backup.zip’ );
echo ‘Finished.’ ;
// Here the magic happens 🙂
function zipData ( $ source , $ destination )
if (extension_loaded( ‘zip’ ))
if (file_exists( $ source ))
$ zip = new ZipArchive ();
if ( $ zip -> open ( $ destination , ZIPARCHIVE :: CREATE ))
$ source = realpath( $ source );
if (is_dir( $ source ))
$ files = new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ source , RecursiveDirectoryIterator :: SKIP_DOTS ), RecursiveIteratorIterator :: SELF_FIRST );
foreach ( $ files as $ file )
$ file = realpath( $ file );
if (is_dir( $ file ))
$ zip -> addEmptyDir (str_replace( $ source . ‘/’ , » , $ file . ‘/’ ));
> else if (is_file( $ file ))
$ zip -> addFromString (str_replace( $ source . ‘/’ , » , $ file ), file_get_contents( $ file ));
>
>
> else if (is_file( $ source ))
$ zip -> addFromString (basename( $ source ), file_get_contents( $ source ));
>
>
return $ zip -> close ();
>
>
return false ;
>
?>

Источник

menzerath / backup.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/*
* PHP Recursive Backup-Script to ZIP-File
* (c) 2012: Marvin Menzerath. (http://menzerath.eu)
*/
// Make sure the script can handle large folders/files
ini_set( ‘max_execution_time’ , 600 );
ini_set( ‘memory_limit’ , ‘1024M’ );
// Start the backup!
zipData( ‘/path/to/folder’ , ‘/path/to/backup.zip’ );
echo ‘Finished.’ ;
// Here the magic happens 🙂
function zipData ( $ folder , $ zipTo )
if (extension_loaded( ‘zip’ ) === true )
if (file_exists( $ source ) === true )
$ zip = new ZipArchive ();
if ( $ zip -> open ( $ destination , ZIPARCHIVE :: CREATE ) === true )
$ source = realpath( $ source );
if (is_dir( $ source ) === true )
$ files = new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ source ), RecursiveIteratorIterator :: SELF_FIRST );
foreach ( $ files as $ file )
$ 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 ();
>
>
return false ;
>
?>

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHPBackupScript — Backup Util Script!

License

StefanSchomacker/PHPBackupScript

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This script is meant to be used on platforms, where only a limited toolset is provided (e.g. no bash scripts are allowed). The concept is intentionally kept simple: the file Backup.php contains the complete logic to back up files and mysql databases.

  • Backup of all files
  • Select own directory for zip backups
  • Except backup directory
  • Log-file
  • Delete old backups after X days
  • MySQL database backup

It is only one PHP File to include. Please make sure that you have the following extension installed on your system:

Download Zip

git clone https://github.com/StefanSchomacker/PHPBackupScript 

Sample Setup

Create a string with the path of your backup directory.

$backupPath = "/var/www/html/backup/"; 

Create an object of Backup::class

$backup = new Backup($backupPath); 
$backup->setDeleteBackupsAfter(20); //deletes archives older than 20 days 
$dirPath = "/var/www/html/"; $backup->backupDirectory($dirPath); $databaseHost = "localhost"; $databaseUser = "user"; $databasePassword = "password"; $databaseName = "databaseName"; $backup->backupDatabase($databaseHost, $databaseUser, $databasePassword, $databaseName); 

Create a new cron entry with crontab -e . The example creates a backup every day at 1am:

0 1 * * * /usr/bin/php [PATH TO Backup.php] 
variable default value description
$_deleteBackupsAfter 30 old zip backup will be deleted. -1 disabled
$_phpTimeoutTime 600 max_execution_time in seconds — to avoid php timeouts

A PHP script will be canceled by default after 30 seconds by the server. The backup could take more time. To avoid the timeout, I set the max_execution_time to 10 minutes. If you need more time, feel free to change the time (in seconds).

Backup directory

The directory of your backups is excluded in every zip archive.

The default name of an archive is backup_Y-m-d_H-i-s .

The logfiles are created in the subdirectory log . Please set up an external log rotation.

Please check your zip backups regularly. Check the log files if archive is broken.

Feel free to create a new Issue or a Pull request

Copyright 2016 Stefan Schomacker Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

About

PHPBackupScript — Backup Util Script!

Источник

Простой бэкап сайта средствами PHP

В этой статье я попытаюсь разъяснить создание простого скрипта для полного бэкапа сайта (файлы + база данных MySQL) средствами PHP, который будет отправлять отчет на почту и удалять старые архивы.

Для начала нужен FTP доступ к файловой системе, где расположен сайт. Предположим, что сайт у нас находится по адресу /home/my_site/www. Создаем папку backup в my_site:

И конечно же, сам файл backup.php:

touch /home/my_site/www/backup.php 

Открываем backup.php любым редактором и создаем переменные:

$backup_folder = '/home/my_site/backup'; // куда будут сохранятся файлы $backup_name = 'my_site_backup_' . date("Y-m-d"); // имя архива $dir = '/home/my_site/www'; // что бэкапим $delay_delete = 30 * 24 * 3600; // время жизни архива (в секундах) $db_host = 'example.com'; $db_user = 'root'; $db_password = 'password'; $db_name = 'database'; $mail_to = 'my_email@example.com'; $mail_subject = 'Site backup'; $mail_message = ''; $mail_headers = 'MIME-Version: 1.0' . "\r\n"; $mail_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $mail_headers .= 'To: me ' . "\r\n"; $mail_headers .= 'From: my_site ' . "\r\n"; 

Пишем функцию для бэкапа файлов:

function backupFiles($backup_folder, $backup_name, $dir) < $fullFileName = $backup_folder . '/' . $backup_name . '.tar.gz'; shell_exec("tar -cvf " . $fullFileName . " " . $dir . "/* "); return $fullFileName; >
function backupDB($backup_folder, $backup_name) < $fullFileName = $backup_folder . '/' . $backup_name . '.sql'; $command = 'mysqldump -h' . $db_host . ' -u' . $db_user . ' -p' . $db_password . ' ' . $db_name . ' >' . $fullFileName; shell_exec($command); return $fullFileName; > 

И для удаления старых архивов:

function deleteOldArchives($backup_folder, $delay_delete) < $this_time = time(); $files = glob($backup_folder . "/*.tar.gz*"); $deleted = array(); foreach ($files as $file) < if ($this_time - filemtime($file) >$delay_delete) < array_push($deleted, $file); unlink($file); >> return $deleted; > 

В общем все, осталось выполнить данные функции и отправить письмо:

$start = microtime(true); // запускаем таймер $deleteOld = deleteOldArchives($backup_folder, $delay_delete); // удаляем старые архивы $doBackupFiles = backupFiles($backup_folder, $backup_name, $dir); // делаем бэкап файлов $doBackupDB = backupDB($backup_folder, $backup_name); // и базы данных // добавляем в письмо отчеты if ($doBackupFiles) < $mail_message .= 'site backuped successfully
'; $mail_message .= 'Files: ' . $doBackupFiles . '
'; > if ($doBackupDB) < $mail_message .= 'DB: ' . $doBackupDB . '
'; > if ($deleteOld) < foreach ($deleteOld as $val) < $mail_message .= 'File deleted: ' . $val . '
'; > > $time = microtime(true) - $start; // считаем время, потраченое на выполнение скрипта $mail_message .= 'script time: ' . $time . '
'; mail($mail_to, $mail_subject, $mail_message, $mail_headers); // и отправляем письмо

Источник

Читайте также:  All java classes and interfaces
Оцените статью