PHP脚本下载Google Drive文本文件遇403错误,求修复方案
解决Google Drive文本文件下载内容异常的问题
问题根源
你的代码出现403权限错误,核心原因有两个:
- 错误使用
export接口:该接口仅用于Google原生文档(如Docs、Sheets)的格式转换,普通.txt文本文件不需要调用它。 - 手动拼接的下载URL未携带授权信息:虽然初始化了授权客户端,但直接构造的HTTP请求没有自动带上服务账号的授权Token,导致请求被判定为无权限。
修正后的代码
<?php require 'vendor/autoload.php'; putenv('GOOGLE_APPLICATION_CREDENTIALS=D:\username\folder\credentials.json'); function downloadFilesFromFolder($folderId, $destinationPath, $service) { // 确保本地目标文件夹存在 if (!is_dir($destinationPath)) { mkdir($destinationPath, 0777, true); } $pageToken = null; do { $parameters = array( 'q' => "'$folderId' in parents and mimeType='text/plain'", 'fields' => 'files(id, name)', 'pageToken' => $pageToken, ); $results = $service->files->listFiles($parameters); if (count($results->getFiles()) == 0) { print "指定文件夹中未找到文本文件。\n"; } else { foreach ($results->getFiles() as $file) { $fileId = $file->getId(); $fileName = $file->getName(); $localFilePath = $destinationPath . DIRECTORY_SEPARATOR . $fileName; try { // 使用Drive API标准方法下载文件,自动携带授权信息 $service->files->get($fileId, array( 'alt' => 'media', 'sink' => $localFilePath )); echo "已下载:$fileName\n"; } catch (Exception $e) { echo "下载失败:$fileName,错误信息:" . $e->getMessage() . "\n"; } } } $pageToken = $results->getNextPageToken(); } while ($pageToken); } $folderId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $destinationPath = 'D:\\username\\folder\\'; $client = new Google_Client(); $client->useApplicationDefaultCredentials(); // 缩小权限范围,遵循最小权限原则 $client->setScopes(Google_Service_Drive::DRIVE_READONLY); $service = new Google_Service_Drive($client); downloadFilesFromFolder($folderId, $destinationPath, $service);
关键修改说明
- 替换下载逻辑:用
$service->files->get()方法并设置alt=media,这是Drive API下载普通文件的标准方式,会自动携带授权Token,避免权限错误。 - 增加文件夹检查:提前创建本地目标文件夹,避免因路径不存在导致的写入失败。
- 优化权限范围:将权限从
DRIVE改为DRIVE_READONLY,仅申请必要权限,提升安全性。 - 异常捕获:添加try-catch块,方便排查下载失败的具体原因。
额外注意事项
- 确保服务账号的邮箱已被添加到目标Google Drive文件夹的共享列表中,且拥有至少查看者权限。
- 确认
credentials.json文件路径正确,文件本身有效且未过期。
内容的提问来源于stack exchange,提问作者ebg
相关产品推荐
相关产品推荐

