PHP code example of open-php / google-drive-uploader

1. Go to this page and download the library: Download open-php/google-drive-uploader library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

open-php / google-drive-uploader example snippets


use Open\GoogleDrive\GoogleDriveService;

$credentialsPath = 'path/to/credentials.json';
$tokenPath = 'path/to/token.json'; // This file will be created/updated automatically

$drive = new GoogleDriveService($credentialsPath, $tokenPath);

if (!file_exists($tokenPath)) {
    // Generate Auth URL
    $authUrl = $drive->getAuthUrl('http://localhost/callback.php');
    echo "Open this URL in your browser:\n$authUrl\n";
    
    // After user grants permission, Google redirects to your callback with a ?code=...
    // Exchange code for token:
    // $code = $_GET['code'];
    // $drive->authenticate($code); // This saves the token to $tokenPath
}

try {
    $localFilePath = '/path/to/image.jpg';
    // Slash-separated paths create nested folders when needed.
    $folderName = 'My Uploads/Photos';
    
    // Upload file
    $fileId = $drive->uploadFile($localFilePath, $folderName);
    
    // uploadFile returns a Google Drive file object.
    echo "File Uploaded! ID: " . $fileId->id . "\n";
    echo "Web View Link: " . $fileId->getWebViewLink() . "\n";
    
    // For images (<img src="...">), use the embed link:
    echo "Embed Link: " . $drive->getEmbedLink($fileId->id);
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}


$files = ['/path/to/img1.jpg', '/path/to/img2.png'];
$uploadedFiles = $drive->uploadFiles($files, 'My Holiday');

foreach ($uploadedFiles as $path => $file) {
    echo "Uploaded $path -> ID: " . $file->id . "\n";
}

try {
    $fileId = '12345abcde...';
    $drive->deleteFile($fileId);
    echo "File deleted successfully.";
} catch (Exception $e) {
    echo "Error deleting file: " . $e->getMessage();
}

try {
    $fileId = '12345abcde...';
    $newName = 'My New Name.jpg';
    
    $updatedFile = $drive->renameFile($fileId, $newName);
    
    echo "File renamed to: " . $updatedFile->getName();
} catch (Exception $e) {
    echo "Error renaming file: " . $e->getMessage();
}

try {
    $drive->downloadFile('GOOGLE_DRIVE_FILE_ID', '/path/to/downloads/report.pdf');
    echo "File downloaded.";
} catch (Exception $e) {
    echo "Error downloading file: " . $e->getMessage();
}

use App\Http\Controllers\DriveController;

Route::post('/upload', [DriveController::class, 'upload'])->name('google.upload');
Route::get('/google/callback', [DriveController::class, 'callback'])->name('google.callback');

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Open\GoogleDrive\GoogleDriveService;
use Exception;

class DriveController extends Controller
{
    private function getDriveService()
    {
        return new GoogleDriveService(
            storage_path('app/google/credentials.json'),
            storage_path('app/google/token.json')
        );
    }

    public function upload(Request $request)
    {
        $request->validate(['file' => '> $googleFile->getWebViewLink(),
                'embed_link' => $drive->getEmbedLink($googleFile->id)
            ]);

        } catch (Exception $e) {
            // Check for "Auth Required" message from library
            if (str_contains($e->getMessage(), 'Google Drive Auth Required')) {
                // Generate Login URL with the callback route
                // IMPORTANT: This route() must match the URI in Google Console
                $authUrl = $this->getDriveService()->getAuthUrl(route('google.callback'));
                return redirect($authUrl);
            }
            throw $e;
        }
    }

    public function callback(Request $request)
    {
        $code = $request->input('code');
        if (!$code) {
             return response()->json(['error' => 'No code provided'], 400);
        }

        $drive = $this->getDriveService();
        
        // Exchange code for token and save it automatically
        $drive->authenticate($code, route('google.callback'));

        return "Token saved! You can now try uploading again.";
    }
}

return view('googleFileView', [
    'fileId' => $googleFile->id,
    'mimeType' => $googleFile->mimeType,
    'embedLink' => $drive->getEmbedLink($googleFile->id), // For Full Images
    'thumbnailLink' => $drive->getThumbnailLink($googleFile->id, 500), // For Smaller/Safer Images
    'previewLink' => $drive->getPreviewLink($googleFile->id) // For Videos/PDFs
]);