Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Google drive API without user interaction using PHP

I want to upload files to Google Drive using the API, but I need to do this using a cron job (autobackup of webfiles+sql to Google drive).

That means (I suppose) that I need to authenticate using something else than the user interaction method.

The example that I have been using: https://developers.google.com/api-client-library/php/auth/web-app to get me going, and its working with user authenticating.

I would appreciate some tips on how to do this without user interaction, so it can run on a cronjob.

Here are the PHP code for authenticate and upload file (working example with manual user auth and single file upload)

  <?php

    require_once 'google-api-php-client/vendor/autoload.php';

    /* Config */
    $servername = 'content here';
    $redirect_uri = 'https://example.com/';

    $client = new Google_Client();
    $client->setAuthConfig('client_manual_authentiation.json');
    $client->addScope(Google_Service_Drive::DRIVE);

    if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {

        $client->setAccessToken($_SESSION['access_token']);
        $drive = new Google_Service_Drive($client);

        foreach($drive->files->listFiles(array("q" => "name = '{$servername}'"))->getFiles() as $key => $element){

            if($element->name == $servername){

                //create todays folder on Google Drive
                $today_folder_meta = new Google_Service_Drive_DriveFile(array(
                    'name' => 'myfile.txt',
                    'mimeType' => 'application/vnd.google-apps.folder',
                    'parents' => array($element['id'])
                ));

                $today_folder = $drive->files->create($today_folder_meta, array(
                    'fields' => 'id'
                ));

            }
        }
    }else{

        if (!isset($_GET['code'])) {
            $auth_url = $client->createAuthUrl();
            header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
        } else {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        }
    }

?>
like image 706
sdfgg45 Avatar asked Oct 16 '25 07:10

sdfgg45


1 Answers

To do this, you want to create a Google OAuth2 Service Account. You can then download a set of JSON credentials that your app will use to authenticate without user interaction.

This is described in the following article:

Using OAuth 2.0 for Server to Server Applications

  • https://developers.google.com/identity/protocols/OAuth2ServiceAccount

You will then be able to download credentials like the following to use in your app:

{
    "type":"service_account",
    "project_id":"your-project-id",
    "private_key_id":"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
    "private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...4XIk=\n-----END PRIVATE KEY-----\n",
    "client_email":"[email protected]",
    "client_id":"12345678901234567890",
    "auth_uri":"https://accounts.google.com/o/oauth2/auth",
    "token_uri":"https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/foobar%40bazqux.iam.gserviceaccount.com"
}

Here is a Google PHP example of how to use this:

  • https://github.com/google/google-api-php-client/blob/master/examples/service-account.php

You can create the Service Account in the Google API Console as shown here:

enter image description here

like image 125
Grokify Avatar answered Oct 18 '25 22:10

Grokify



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!