PHP - Problems uploading with Google Drive API

Asked

Viewed 868 times

0

Good night.

I am trying to upload with the Google Drive API using the following PHP code:

<?php

require_once 'src/Google/Client.php';
require_once 'src/contrib/Google_DriveService.php';
require_once __DIR__.'/vendor/autoload.php';


$client_id = 'YOUR CLIENT ID';
$client_secret = 'YOUR CLIENT SECRET';
$redirect_uri = 'http://localhost/modeloImpacto.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
//$client->addScope("https://www.googleapis.com/auth/drive");
 $client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);

$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'funcionou.jpg'));
$content = file_get_contents('funcionou.jpg');
$file = $driveService->files->create($fileMetadata, array(
  'data' => $content,
  'mimeType' => 'image/jpeg',
  'uploadType' => 'multipart',
  'fields' => 'id'));
printf("File ID: %s\n", $file->id);

?>

But I come across the following error message:

Fatal error: Class 'Google_serviceresource' not found in C: wamp64 www src contrib Google_driveservice.php on line 25

Someone knows what’s missing?

Thank you! Raffael Siqueira.

  • Just for one test, put this line require_once DIR.'/vendor/autoload.php'; before the other requires...

  • Rodrigo, thanks for the tip! But the error persisted the same, unfortunately.

1 answer

0

I managed to run a PHP added in CRON. It asks for the verification code only the first time and then everything works. I’ve been running the CRON for over 16 hours and everything is working perfectly.

Well, considering you’ve already done the steps:

  • Create a Project in Google Cloud Platform;
  • In Credentials, you already have the Oauth 2.0 Client ID;
  • Downloaded credentials and renamed to credentials.json;
  • Used Composer to download Google Drive libraries;

References in:

https://developers.google.com/drive/api/v3/quickstart/php https://developers.google.com/drive/api/v3/reference/files/create https://developers.google.com/drive/api/v3/manage-uploads

this code here is the result of a "working" upload to Google Drive in a specific subfolder. I hope it helps.

<?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);

}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.