PHP 脚本功能说明
该 PHP 脚本用于将指定时间之后修改的文件压缩到一个名为 update.zip
的文件中。它会排除特定的目录和文件后缀,以确保只压缩需要的文件。
功能要点
- 日期参数: 可以通过命令行传递一个日期时间参数。如果没有提供参数,默认使用当天的开始时间(
00:00:00
)。 - 排除规则: 脚本会排除指定的目录(如
runtime
)和文件后缀(如.log
、.zip
)。 - 文件压缩: 只会压缩指定时间后修改的文件,并将它们打包到
update.zip
中。
代码解析
<?php
// 检查是否传入了时间参数,默认使用当天零点
if ($argc < 2) {
$specifiedTime = strtotime(date('Y-m-d 00:00:00'));
} else {
$specifiedTime = strtotime($argv[1]);
}
// 检查时间格式是否有效
if ($specifiedTime === false) {
echo "Invalid date format. Please use 'YYYY-MM-DD HH:MM:SS'.\n";
exit(1);
}
// 定义排除的目录和文件后缀
$excludeDirs = ['runtime'];
$excludeExtensions = ['log','zip'];
// 生成排除目录的正则表达式
$excludeDirPattern = '#^(' . implode('|', array_map(function ($dir) {
return preg_quote($dir, '#');
}, $excludeDirs)) . ')#i';
// 生成排除文件后缀的正则表达式
$excludeExtPattern = '#\.(' . implode('|', array_map(function ($ext) {
return preg_quote($ext, '#');
}, $excludeExtensions)) . ')$#i';
$zip = new ZipArchive();
$zipFileName = 'update.zip';
// 打开或创建 zip 文件
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
exit("Cannot open <$zipFileName>\n");
}
// 遍历当前目录及其子目录的文件
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$fileModTime = filemtime($filePath);
// 获取相对路径
$relativePath = substr($filePath, strlen(getcwd()) + 1);
// 检查是否在排除的目录中
if (preg_match($excludeDirPattern, $relativePath)) {
continue;
}
// 检查是否有排除的文件后缀
if (preg_match($excludeExtPattern, $filePath)) {
continue;
}
// 检查文件是否在指定时间后被修改
if ($fileModTime >= $specifiedTime) {
$zip->addFile($filePath, $relativePath);
}
}
}
// 关闭 zip 文件
$zip->close();
echo "Files have been zipped to $zipFileName\n";
使用方法
- 将代码保存为 PHP 文件(例如
backup.php
)。 - 在命令行中运行脚本,支持以下两种方式:
- 默认使用当天的开始时间:
php backup.php
- 指定日期时间参数:
php backup.php "2024-08-26 10:00:00"
- 默认使用当天的开始时间:
- 脚本将生成一个名为
update.zip
的文件,其中包含在指定时间后修改且不在排除列表中的文件。
注意事项
- 日期格式应为
'YYYY-MM-DD HH:MM:SS'
。 - 可以根据需要修改
$excludeDirs
和$excludeExtensions
变量,以排除其他目录或文件类型。