Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
谷歌驱动PHP API-简单文件上传_Php_Google Drive Api_Google Api Php Client - Fatal编程技术网

谷歌驱动PHP API-简单文件上传

谷歌驱动PHP API-简单文件上传,php,google-drive-api,google-api-php-client,Php,Google Drive Api,Google Api Php Client,我正在尝试编写一个小脚本,使用GoogleDrivePHPAPI将本地文件上传到GoogleDrive。文档的维护非常差,但到目前为止,我非常确定代码应该是这样的: <?php include_once 'Google/Client.php'; include_once 'Google/Service/Drive.php'; include_once 'Google/Auth/OAuth2.php'; $client = new Google_Client(); $client-&g

我正在尝试编写一个小脚本,使用GoogleDrivePHPAPI将本地文件上传到GoogleDrive。文档的维护非常差,但到目前为止,我非常确定代码应该是这样的:

<?php

include_once 'Google/Client.php';
include_once 'Google/Service/Drive.php';
include_once 'Google/Auth/OAuth2.php';

$client = new Google_Client();

$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setClientId('dfgdfgdg');
$client->setClientSecret('dfgdfgdf');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');


$service = new Google_Service_Drive($client);

$data = file_get_contents("a.jpg");

// create and upload a new Google Drive file, including the data
try
{
//Insert a file
$file = new Google_Service_Drive_DriveFile($client);

$file->setTitle(uniqid().'.jpg');
$file->setMimeType('image/jpeg');

$createdFile = $service->files->insert($file, array(
    'data' => $data,
    'mimeType' => 'image/jpeg',
    'uploadType' => 'media',
));
}
catch (Exception $e)
{
    print $e->getMessage();
}

print_r($createdFile);

?>
然后是此错误:

Notice: Undefined variable: createdFile in C:\wamp\www\GoogleAPI\index.php on line 39
我做错了什么?您能否提供一个简单的工作脚本,使用GoogleDrivePHPAPI将文件上传到GoogleDrive?提前谢谢你

用这个

<?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 console
    $client->setClientId('YOUR_CLIENT_ID');
    $client->setClientSecret('YOUR_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();
    $localfile = 'a.jpg';
    $title = basename($localfile);
    $file->setTitle($title);
    $file->setDescription('My File');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents($localfile);

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

    print_r($createdFile);
    ?>

使用此代码验证和上载测试文件。您需要将
(也在控制台中)设置到此文档本身以进行身份验证

require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('<YOUR_CLIENT_ID>');
$client->setClientSecret('<YOUR_CLIENT_SECRET>');
$client->setRedirectUri('<YOUR_REGISTERED_REDIRECT_URI>');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));

session_start();

if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
    } else
        $client->setAccessToken($_SESSION['access_token']);

    $service = new Google_Service_Drive($client);

    //Insert a file
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents('a.jpg');

    $createdFile = $service->files->create($file, array(
          'data' => $data,
          'mimeType' => 'image/jpeg',
          'uploadType' => 'multipart'
        ));

    print_r($createdFile);

} else {
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
    exit();
}
require_once'Google/Client.php';
需要一次“Google/Service/Drive.php”;
$client=新的Google_客户端();
//从控制台获取您的凭据
$client->setClientId(“”);
$client->setClientSecret(“”);
$client->setRedirectUri(“”);
$client->setScopes(阵列)https://www.googleapis.com/auth/drive.file'));
会话_start();
如果(isset($_GET['code'])| |(isset($_SESSION['access\u token'])和&$_SESSION['access\u token'])){
如果(isset($_GET['code'])){
$client->authenticate($_GET['code']);
$\会话['access\u token']=$client->getAccessToken();
}否则
$client->setAccessToken($_会话['access_token']);
$service=新的谷歌服务驱动器($client);
//插入文件
$file=新的Google_服务_驱动器_驱动器文件();
$file->setName(uniqid()..jpg');
$file->setDescription(“测试文档”);
$file->setMimeType('image/jpeg');
$data=file_get_contents('a.jpg');
$createdFile=$service->files->create($file,array)(
“数据”=>$data,
'mimeType'=>'image/jpeg',
“uploadType”=>“多部分”
));
打印文件($createdFile);
}否则{
$authUrl=$client->createAuthUrl();
标题('Location:'。$authUrl);
退出();
}

我能够运行添加到CRON中的PHP。他只在第一次要求验证码,然后一切正常。我已经运行CRON超过16小时了,一切都很好

考虑到你已经完成了以下步骤:

  • 在谷歌云平台上创建项目
  • 在凭据中,您已经拥有OAuth 2.0客户端ID
  • 下载凭据并重命名为credentials.json
  • 使用composer下载谷歌硬盘库 参考资料:

    这里的代码是在特定子文件夹中上传到Google Drive的“工作”结果。我希望有帮助

    <?php
    
    ini_set('memory_limit', '4096M');
    
    require __DIR__ . '/vendor/autoload.php';
    
    function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('Google Drive API PHP Quickstart');
        $client->setScopes(Google_Service_Drive::DRIVE);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
    
    
        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = 'token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->setAccessToken($accessToken);
        }
    
        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));
    
                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                $client->setAccessToken($accessToken);
    
                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }
    
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Drive($client);
    
    // Print the names and IDs for up to 10 files.
    // Esse resultado é importante para ver que tudo está concetado;
    // Esse comando deve exibir as ultimas 3 atividades do seu drive;
    $optParams = array(
      'pageSize' => 3,
      'fields' => 'nextPageToken, files(id, name)'
    );
    $results = $service->files->listFiles($optParams);
    
    if (count($results->getFiles()) == 0) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($results->getFiles() as $file) {
            printf("%s (%s)\n", $file->getName(), $file->getId());
        }
    }
    //
    // Fim atividades do Drive;
    //
    
    
    //Define variáveis de arquivos
    //Aqui você pode substituir depois par algum array ou resultado do banco de dados
    //Defina um bem simples inicialmente para ver que tudo funciona
    $pasta      = 'substitua pela pasta';   // Um exemplo aqui é /home/usuario/public_html/arquivos_upload
    $arquivo    = 'substitua pelo arquivo'; // arquivo.mp4
        printf("Pasta: %s || Arquivo: %s\n", $pasta, $arquivo);
    }
    
    //Essa é a pasta destino do Google Drive
    $parentId   = 'substitua pelo ID da Pasta';
    
    
    if ( !empty($arquivo) ) {
    
        //Define localização da pasta e arquivo
        $file_path = $pasta.'/'.$arquivo;
    
        //Conecta no Drive da sua conta
        $file = new Google_Service_Drive_DriveFile();
    
        //Define nome do arquivo
        $file->setName($arquivo);
    
        //Define Diretório Destino lá no Google Drive
        $file->setParents(array($parentId));
    
        //Cria o arquivo no GDrive
        $service->files->create(
          $file,
          array(
            'data'          => file_get_contents($file_path),
            'mimeType'      => 'application/octet-stream',
            'uploadType' => 'resumable'
          )
        );
    
        // Grava Log do que foi feito UTC -3 horas;
        $DateTime = new DateTime();
        $DateTime->modify('-3 hours');
        $now = $DateTime->format("Y-m-d H:i:s");
        $logfile = $now.' Upload OK :: '.$arquivo.PHP_EOL;
    
        $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);
    
    } else {
    
        //Grava Log
        $now = date("Y-m-d H:i:s");
        $logfile .=$now.' =====SEM ARQUIVOS========'.PHP_EOL;
    
        $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);
    
    }
    
    ?>
    
    
    
    感谢您的回答,不幸的是,这是一个老例子,已经被谷歌弃用了。甚至包括的文件都被更改了。请给我发送最新的api链接谢谢你的回答!我认为你提供的脚本非常接近我需要的东西。在我以前的版本中,我成功地获得了$_get['code']值。使用您的脚本版本也可以。我的URL改为:这意味着代码正常。不幸的是,紧接着我就收到了这些错误:致命错误:未捕获异常“Google\u IO\u exception”,消息为“HTTP错误:无法连接:'fopen()[]:未能在C:\wamp\www\GoogleAPI\Google\IO\stream.php的第112行打开流:无效参数”“,服务器中的某些配置可能会修复此问题,我在操作系统中搜索了你的错误,发现这个:它成功了!非常感谢,我可以确认脚本正在运行!另一个问题->有人问我是否接受与应用程序交互的脚本。我可以在将来自动进行此授权吗?提前谢谢你!没关系,我遵循了你的另一个答案,我已经自动化了这个过程!非常感谢。
    <?php
    
    ini_set('memory_limit', '4096M');
    
    require __DIR__ . '/vendor/autoload.php';
    
    function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('Google Drive API PHP Quickstart');
        $client->setScopes(Google_Service_Drive::DRIVE);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
    
    
        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = 'token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->setAccessToken($accessToken);
        }
    
        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));
    
                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                $client->setAccessToken($accessToken);
    
                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }
    
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Drive($client);
    
    // Print the names and IDs for up to 10 files.
    // Esse resultado é importante para ver que tudo está concetado;
    // Esse comando deve exibir as ultimas 3 atividades do seu drive;
    $optParams = array(
      'pageSize' => 3,
      'fields' => 'nextPageToken, files(id, name)'
    );
    $results = $service->files->listFiles($optParams);
    
    if (count($results->getFiles()) == 0) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($results->getFiles() as $file) {
            printf("%s (%s)\n", $file->getName(), $file->getId());
        }
    }
    //
    // Fim atividades do Drive;
    //
    
    
    //Define variáveis de arquivos
    //Aqui você pode substituir depois par algum array ou resultado do banco de dados
    //Defina um bem simples inicialmente para ver que tudo funciona
    $pasta      = 'substitua pela pasta';   // Um exemplo aqui é /home/usuario/public_html/arquivos_upload
    $arquivo    = 'substitua pelo arquivo'; // arquivo.mp4
        printf("Pasta: %s || Arquivo: %s\n", $pasta, $arquivo);
    }
    
    //Essa é a pasta destino do Google Drive
    $parentId   = 'substitua pelo ID da Pasta';
    
    
    if ( !empty($arquivo) ) {
    
        //Define localização da pasta e arquivo
        $file_path = $pasta.'/'.$arquivo;
    
        //Conecta no Drive da sua conta
        $file = new Google_Service_Drive_DriveFile();
    
        //Define nome do arquivo
        $file->setName($arquivo);
    
        //Define Diretório Destino lá no Google Drive
        $file->setParents(array($parentId));
    
        //Cria o arquivo no GDrive
        $service->files->create(
          $file,
          array(
            'data'          => file_get_contents($file_path),
            'mimeType'      => 'application/octet-stream',
            'uploadType' => 'resumable'
          )
        );
    
        // Grava Log do que foi feito UTC -3 horas;
        $DateTime = new DateTime();
        $DateTime->modify('-3 hours');
        $now = $DateTime->format("Y-m-d H:i:s");
        $logfile = $now.' Upload OK :: '.$arquivo.PHP_EOL;
    
        $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);
    
    } else {
    
        //Grava Log
        $now = date("Y-m-d H:i:s");
        $logfile .=$now.' =====SEM ARQUIVOS========'.PHP_EOL;
    
        $myfile = file_put_contents('logs.txt', $logfile, FILE_APPEND | LOCK_EX);
    
    }
    
    ?>