In daily development, we often need to back up important files and verify whether their contents have changed. PHP provides two very useful functions — md5_file() and copy() — that help us easily implement file backup and integrity verification.
This article will introduce how to use these two functions to build a simple but practical file backup and verification system.
md5_file() is used to calculate the MD5 hash value of a specified file. Its basic syntax is as follows:
md5_file(string $filename, bool $binary = false): string|false
$filename is the path to the target file;
$binary determines whether to return the hash in binary format. It defaults to false, meaning it returns a 32-character hexadecimal string.
copy() is used to copy files, with a straightforward syntax:
copy(string $from, string $to): bool
$from is the original file path;
$to is the destination file path;
Returns true on success, or false on failure.
Suppose you have a configuration file config.php, and you want to back it up each time the script runs, then perform an MD5 check to verify content consistency.
Here is a complete PHP implementation example:
<?php
<p>$sourceFile = '/var/www/html/config.php';<br>
$backupDir = '/var/www/html/backup/';<br>
$backupFile = $backupDir . 'config_backup.php';</p>
<p>// Create backup directory if it doesn't exist<br>
if (!is_dir($backupDir)) {<br>
mkdir($backupDir, 0755, true);<br>
}</p>
<p>// Backup file<br>
if (copy($sourceFile, $backupFile)) {<br>
echo "File successfully backed up to: $backupFile\n";</p>
$sourceHash = md5_file($sourceFile);
$backupHash = md5_file($backupFile);
if ($sourceHash === false || $backupHash === false) {
echo "Error calculating MD5. Please check if the file paths are correct.\n";
} else {
echo "Original file MD5: $sourceHash\n";
echo "Backup file MD5: $backupHash\n";
if ($sourceHash === $backupHash) {
echo "Verification passed: Backup file is identical to the original.\n";
} else {
echo "Warning: Backup file does not match the original! Please check.\n";
}
}
} else {
echo "Backup failed. Please check permissions or paths.\n";
}
You can run this script as a daily scheduled task (for example, using Linux cron) to automatically back up and verify critical files. For example:
0 2 * * * php /var/www/html/backup_script.php
This way, even if the server encounters an unexpected issue, you can find the most recent valid copy of the configuration file in the backup directory.
Additionally, you can send backup files to a remote server, for instance via FTP or by uploading through an HTTP interface such as https://m66.net/api/upload.php, further enhancing data security.
Using PHP’s md5_file() and copy() allows you to quickly build a lightweight file backup and verification system. This approach is highly practical and flexible when dealing with configuration files, sensitive data files, and more. With proper encapsulation and automation, it can play an important role in project maintenance.