Backup Script in PHP

Uwaga! Informacje na tej stronie mają ponad 5 lat. Nadal je udostępniam, ale prawdopodobnie nie odzwierciedlają one mojej aktualnej wiedzy ani przekonań.

# Backup Script in PHP

11:46
Sun
02
Aug 2009

One of my personal security procedures is daily backup of the code I'm working on to my FTP server. This process requires packing files to an archive and upload the archive to the FTP server. Most annoying part when doing it manually was always selecting aproppriate files, without all these big temporary files and directories like Debug, Release, .ncb, .suo, .user etc.

Today in the morning I've decided to automate this backup task with a script. As I like to use PHP as shell scripting language, here is my backup script in PHP: Backup.php_. It was not a suprise for me to see that PHP already have all the functionality I need, including building ZIP archive and FTP client. Some comments to my code:

To run the script, you must have PHP installed. Then you can just enter something like this into command line:

php Backup.php D:\MyGreatProject

Or you can create BAT file to support backup of your particular project:

@php D:\Backup.php D:\MyGreatProject
@pause

After the script have been started, you have to enter "backup name". It is the name of the ZIP file that will be uploaded to FTP. Script recursively searches for files and subdirectories in the given project directory, filters them using functions FilterDir and FilterFile, packs them to a temporary archive file and then uploads the archive to the FTP server. All remaining parameters (temporary archive path, FTP hostname, login, password and remote directory) are hardcoded as constants.

When it comes to the script code, one of the issues was to ask user about the backup name using system console. PHP has an extension called Readline, but unfortunately it doesn't work on Windows. The solution was to use fgets function with STDIN constant:

print("Enter backup name (default: \"$sSuggestedBackupName\"): ");
$sBackupName = trim(fgets(STDIN, 1024));
if (!$sBackupName)
  $sBackupName = $sSuggestedBackupName;

When it comes to building ZIP archive and handling FTP connection, PHP also has extensions for that and they seem to just work in my PHP without any problems. Zip extension exposes class ZipArchive and FTP extension exposes functions ftp_, like ftp_connect or ftp_put. All is documented in the official PHP documentation.

Comments | #scripts #php #tools Share

Comments

STAT NO AD
[Stat] [STAT NO AD] [Download] [Dropbox] [pub] [Mirror]
Copyright © 2004-2017