<?php
// 远程文件地址
define('REMOTE_FILE_ADDRESS', 'https://example.com/uploads.zip');
// 下载时间段(24小时格式)
define('DOWNLOAD_TIME', 13);
// 休眠时间(以秒为单位)
define('SLEEP_TIME', 60 * 30);
// 文件存储目录
define('STORAGE_DIR', __DIR__ . '/file');
// 错误日志
define('ERROR_LOG', __DIR__ . '/error.log');
// 循环时每次读取字节
define('READ_SIZE', 1024);
while (true) {
try {
$localFileName = STORAGE_DIR . '/' . date('Ymd') . '.zip';
if (!file_exists($localFileName) && (date('H') == DOWNLOAD_TIME)) {
// 打开远程文件
$openRemoteFIle = fopen(REMOTE_FILE_ADDRESS, 'r');
if (!$openRemoteFIle) {
throw new Exception("打开远程文件失败\n");
}
// 创建存储目录
if (!is_dir(STORAGE_DIR)) {
if (!mkdir(STORAGE_DIR, 0777, true)) {
throw new Exception("新建存储目录失败\n");
}
}
// 打开本地文件
$openLocalFile = fopen($localFileName, 'w');
if (!$openLocalFile) {
throw new Exception("打开本地文件失败\n");
}
// 存储数据
while (!feof($openRemoteFIle)) {
fwrite($openLocalFile, fgets($openRemoteFIle, READ_SIZE));
}
// 关闭文件句柄
fclose($openLocalFile);
fclose($openRemoteFIle);
}
} catch (Exception $exception) {
// 记录错误
file_put_contents(ERROR_LOG, $exception->getMessage());
// 兼容关闭文件句柄
if (isset($openRemoteFIle) && $openRemoteFIle) {
fclose($openRemoteFIle);
}
if (isset($openLocalFile) && $openLocalFile) {
fclose($openLocalFile);
}
}
sleep(SLEEP_TIME);
}