Skip to content

Instantly share code, notes, and snippets.

@KartikWatts
Last active May 10, 2021 08:44
Show Gist options
  • Save KartikWatts/22dc9eb20980b5b4e041ddcaf04caf9e to your computer and use it in GitHub Desktop.
Save KartikWatts/22dc9eb20980b5b4e041ddcaf04caf9e to your computer and use it in GitHub Desktop.
Google Drive V3 API access with PHP
<?php
// Gist for Stack OverFlow answer: https://stackoverflow.com/a/67467388/7610978
//THE API IS ACCESSED HERE USING *Service Account*, you may use other authentication ways as per requirements.
// For more clear reference to the parameters along with a description, this is really helpful: https://developers.google.com/drive/api/v3/reference/permissions#methods
namespace App\Http\Controllers;
use Google_Client;
use Google_Service_Drive;
use Google_Service_Drive_DriveFile;
use Google_Service_Drive_Permission;
class GoogleDrive{
protected $service, $newPermission;
function __construct(){
$client = new Google_Client();
$client->setApplicationName('Demo Google Drive API Access');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
// ``HERE THE CREDENTIALS JSON FILE IS TO BE PROVIDED THAT YOU GET ON CREATING KEY FROM YOUR SERVICE ACCOUNT.
$credentials_data= storage_path()."/json/credentials.json";
$credentials= json_decode(file_get_contents($credentials_data),true);
$client->setAuthConfig($credentials);
$this->service = new Google_Service_Drive($client);
$this->newPermission = new Google_Service_Drive_Permission();
$value=$value=<YOUR EMAIL ADDRESS>;
$type="user";
//IN CASE Type is set to "anyone", remove setEmailAddress method.
// $type="anyone";
$role="reader";
$this->newPermission->setEmailAddress($value);
$this->newPermission->setType($type);
$this->newPermission->setRole($role);
$this->newPermission->allowFileDiscovery;
$this->newPermission->view;
}
public function create_folder( $folder_name, $parent_folder_id=null ){
$folder_list = $this->check_folder_exists( $folder_name );
// if folder does not exists
if( count( $folder_list ) == 0 ){
$folder = new Google_Service_Drive_DriveFile();
$folder->setName( $folder_name );
$folder->setMimeType('application/vnd.google-apps.folder');
if( !empty( $parent_folder_id ) ){
$folder->setParents( [ $parent_folder_id ] );
}
$result = $this->service->files->create( $folder );
$folder_id = null;
if( isset( $result['id'] ) && !empty( $result['id'] ) ){
$folder_id = $result['id'];
}
print_r($folder_id);
return $folder_id;
}
try {
$res= $this->service->permissions->create($folder_list[0]['id'], $this->newPermission);
print_r($res);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return $folder_list[0]['id'];
}
public function get_files_and_folders(){
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $this->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());
}
}
}
public function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ){
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $this->service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => 'application/octet-stream',
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
get_files_and_folders();
return $is_success;
}
public function check_folder_exists( $folder_name ){
$parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and trashed=false";
$files = $this->service->files->listFiles($parameters);
$op = [];
foreach( $files as $k => $file ){
$op[] = $file;
}
return $op;
}
}
class GoogleDriveController extends Controller
{
public function get_drive(){
$drive= new GoogleDrive();
//MANUALLY SETTING THE FILE FROM LOCAL STORAGE
$path= storage_path()."/images/logo_opt.png";
$file_name="logo_opt.png";
//GETTING THE FILE FROM FORM SUBMISSION
// $file_tmp = $_FILES["file"]["tmp_name"];
// $file_type = $_FILES["file"]["type"];
// $file_name = basename($_FILES["file"]["name"]);
// $path = "uploads/".$file_name;
// move_uploaded_file($file_tmp, $path);
//CREATING THE FOLDER PROGRAMATICALLY
// $folder_id = $drive->create_folder( "Ram8" );
$folder_id=<ALREADY CREATED FOLDER ID>; //IN THIS CASE PERMISSION SHALL BE PROVIDED TO SERVICE ACCOUNT USER BEFORE.
$success = $drive->insert_file_to_drive( $path , $file_name, $folder_id);
if( $success ){
echo "file uploaded successfully";
} else {
echo "Something went wrong.";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment