Thursday, April 6

Backup files to google drive using PHP coding

 Dear All,


To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here's an example code snippet that shows how to upload a file to Google Drive:

PHP code

<?php

require_once __DIR__ . '/vendor/autoload.php'; // Include Google Client Library

// Set up the credentials

$client = new Google_Client();

$client->setAuthConfig('client_secret.json'); // Replace with your own credentials file

$client->addScope(Google_Service_Drive::DRIVE_FILE);

// Authenticate the user

if ($client->isAccessTokenExpired()) {

  $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

}

// Create a new Google Drive client

$service = new Google_Service_Drive($client);

// File to upload

$file_path = '/path/to/backup.zip';

$file_name = 'backup.zip';

// Upload file to Google Drive

$file = new Google_Service_Drive_DriveFile();

$file->setName($file_name);

$file->setParents(array('your_folder_id')); // Replace with the ID of the folder to upload the file to

$content = file_get_contents($file_path);

$file = $service->files->create($file, array(

    'data' => $content,

    'mimeType' => 'application/zip',

    'uploadType' => 'multipart'

));

// Print the ID of the newly created file

echo 'File ID: ' . $file->id;

?>

In this code, I first include the Google Client Library using require_once __DIR__ . '/vendor/autoload.php'. Then, I set up the credentials by creating a new Google_Client instance and specifying the location of the credentials file.

Then authenticate the user by fetching the access token with the refresh token, if the access token is expired.

Next, I create a new Google_Service_Drive instance and specify the scope for the Drive API.

I define the file to upload by specifying the file path and name. For specify the ID of the folder to upload the file to.

Finally, I use the files->create() method to upload the file to Google Drive. This method takes the file object and an array of options as parameters. In this case, I specify the file content, MIME type, and upload type.

If the file is uploaded successfully, I print the ID of the newly created file. Note that you need to replace the credentials file and folder ID with your own values.

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...