php 8.6可以通过google drive api的changes集合读取当前授权用户的文件变更。以保存的pagetoken开始,先应用当前页,再保存nextpagetoken;最后一页使用newstartpagetoken作为下次轮询起点。游标不能跨用户或跨同步范围混用。

官方文档:获取起始页令牌 复制指向此部分的链接:获取起始页令牌
先完成用户授权和初始化
启用Drive API,安装google/apiclient:^2.20,并按官方PHP快速入门取得与目标用户一致的预授权凭据。下面使用已配置的应用默认凭据,所需范围为Drive元数据只读;服务账号不会自动获得个人网盘权限。初始化时获取startPageToken,和初始文件快照一起建立状态;仅从当前token开始会跳过此前历史。

官方文档:获取更改 复制指向此部分的链接:获取更改
逐页合并状态并原子保存游标
将drive-state.json放在网站目录外,预先保存cursor字符串和items对象。示例一次最多读取10页;每页写入完成后才推进游标,下次可从剩余页继续。items以文件ID更新或移除,重复读取一页不会新增重复文件。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
$path = __DIR__ . '/drive-state.json';
$lock = fopen($path . '.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) { throw new RuntimeException('Sync already running'); }
$state = json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
if (!is_string($state['cursor'] ?? null) || !is_array($state['items'] ?? null)) { throw new RuntimeException('Invalid state'); }
$client = new Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE_METADATA_READONLY);
$drive = new Drive($client);
try {
for ($page = 0; $page < 10; ++$page) {
$r = $drive->changes->listChanges($state['cursor'], [
'spaces' => 'drive', 'includeRemoved' => true, 'pageSize' => 100,
'fields' => 'nextPageToken,newStartPageToken,changes(fileId,removed,file(id,name,mimeType,modifiedTime))',
]);
foreach ($r->getChanges() as $change) {
$id = $change->getFileId();
if ($change->getRemoved()) { unset($state['items'][$id]); }
elseif ($file = $change->getFile()) {
$state['items'][$id] = ['name' => $file->getName(), 'modified' => $file->getModifiedTime()];
}
}
$next = $r->getNextPageToken();
$cursor = $next ?: $r->getNewStartPageToken();
if (!$cursor) { throw new RuntimeException('Missing continuation token'); }
$state['cursor'] = $cursor;
$json = json_encode($state, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (file_put_contents($path . '.tmp', $json) !== strlen($json) || !rename($path . '.tmp', $path)) {
throw new RuntimeException('Checkpoint write failed');
}
if (!$next) { break; }
}
} finally { flock($lock, LOCK_UN); fclose($lock); }把权限变化和真正删除分开
removed可能表示文件已不在当前变更范围或用户已失去访问权限,不能据此删除远端文件。这个示例只维护本地元数据,不下载文件内容,也不写Google Drive。请求失败时停止当前页,保留旧游标;若业务还要发邮件或调用其他服务,应使用额外的幂等事件记录,不能仅靠本地文件映射保证外部副作用只执行一次。


















