以下是一个简单的PHP脚本实例,用于备份指定的文件或目录。该脚本会创建一个压缩文件,包含指定的文件或目录。
| 步骤 | 说明 |
| --- | --- |
| 1 | 创建一个PHP文件,命名为backup.php |
| 2 | 在文件中添加以下代码: |
```php
// 设置备份文件名
$backupFileName = 'backup_' . date('Y-m-d') . '.zip';
// 设置要备份的文件或目录路径
$sourcePath = '/path/to/your/source/folder/or/file';
// 使用ZipArchive类进行压缩
$zip = new ZipArchive();
$zip->open($backupFileName, ZipArchive::CREATE);
// 如果路径是文件,直接添加到压缩文件中
if (is_file($sourcePath)) {
$zip->addFile($sourcePath);
} else {
// 如果路径是目录,递归添加所有文件
$dirIterator = new RecursiveDirectoryIterator($sourcePath);
$files = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($sourcePath));
if ($file->isFile()) {
$zip->addFile($filePath, $relativePath);
}
}
}
// 关闭压缩文件
$zip->close();
// 输出备份文件名
echo "