2

[编辑]正如错误所指出的,我的 php.ini 为每个脚本分配 1GB 的 RAM(memory_limit = 1G),这应该绰绰有余,所以我不是在问如何增加或修改这个限制。我刚刚发现这个问题可以被认为是这个其他未回答问题的重复:Upload large file to google drive with PHP Client Library

我正在尝试使用google API 快速入门指南中提供的 PHP CLI 脚本从我的 VPS 将一个大文件 (237MB) 上传到我的 google drive 帐户,但出现以下错误:

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted 
(tried to allocate 316952783 bytes) in 
/var/www/google-api-php-client/src/service/Google_MediaFileUpload.php on line 135

剧本:

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('MY_CLIENT_ID');
$client->setClientSecret('MY_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_DriveService($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My zip file');
$file->setDescription('A test zip file');
$file->setMimeType('application/zip');

$data = file_get_contents('myfile.zip');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'application/zip',
    ));

print_r($createdFile);
?>

top 说我有 787816k 可用物理内存(加上 2G 缓存),所以我不知道问题出在哪里。有什么线索吗?

4

1 回答 1

3

[编辑]这是内存分配问题的有效答案,但不能在合理的脚本内存使用限制内解决文件上传问题,这是实际问题。有关该问题的答案,请查看https://stackoverflow.com/a/14693917/1060686

PHP 有一种机制可以防止 PHP 脚本使用超过给定阈值所允许的内存。这个阈值可以在 php.ini 中配置(对于所有脚本)或每个脚本。我建议将每个脚本设置为更高的值。

在脚本顶部添加以下行:

ini_set('memory_limit', '500M');

大内存使用说明:您使用以下行读取文件:

$data = file_get_contents('myfile.zip');

这需要 PHP 将完整的文件内容读入内存(在 var 中$data)。最好是按块读取文件,例如以 4096 字节块的形式,然后立即将它们发送到网络。就像我说的,我目前不知道是否可以使用您正在使用的 google API。

于 2013-03-04T22:57:44.820 回答