内存分配错误的基本谷歌驱动器PHP API上传脚本


Memory allocation error on basic Google Drive PHP API upload script

[EDIT]正如错误指定的那样,我的php.ini为每个脚本分配1GB的RAM (memory_limit = 1G),这应该足够了,所以我不是在问如何增加或修改这个限制。我刚刚发现这个问题可以被认为是另一个重复的未回答的问题:上传大文件到谷歌驱动器与PHP客户端库

我试图上传一个大文件(237MB)到我的谷歌驱动器帐户从我的VPS使用谷歌API的快速入门指南上提供的PHP CLI脚本,我得到以下错误:

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缓存),所以我不知道问题在哪里。有线索吗?

[EDIT]这是内存分配问题的有效答案,但不能在合理的脚本内存使用限制内解决文件上传,这是实际的问题。要了解这个问题的答案,请查看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