PHP code example of pimphand / gdrive

1. Go to this page and download the library: Download pimphand/gdrive 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/ */

    

pimphand / gdrive example snippets


use Pimphand\GDrive\Facades\GDrive;

// Upload file
$file = GDrive::put(
    fileName: 'report.pdf',
    body: $request->getContent(),          // string, resource, or StreamInterface
    mimeType: 'application/pdf',
    sizeBytes: (string) $request->header('Content-Length'), // optional
);

// Response: ['id' => '...', 'name' => '...', 'mime_type' => '...', 'size' => '...']

// Download (returns StreamedResponse)
return GDrive::get($file['id']);

// Inline preview (video/PDF in browser)
return GDrive::get($file['id'], disposition: 'inline');

// Byte-range (video seek)
return GDrive::get($file['id'], range: $request->header('Range'));

// Delete file
GDrive::delete($file['id']);

// List all files in the app folder
$files = GDrive::list();

// Check if file exists
GDrive::exists($file['id']);

// Google Drive web view URL
$viewUrl = GDrive::url($file['id']);

// Sync quota
$quota = GDrive::quota();

use Pimphand\GDrive\GoogleDriveStorage;

class FileController extends Controller
{
    public function __construct(
        private readonly GoogleDriveStorage $storage,
    ) {}

    public function upload(Request $request)
    {
        $file = $this->storage->put(
            $request->file('file')->getClientOriginalName(),
            fopen($request->file('file')->getRealPath(), 'r'),
            $request->file('file')->getMimeType(),
            (string) $request->file('file')->getSize(),
        );

        return response()->json($file);
    }

    public function download(string $fileId)
    {
        return $this->storage->get($fileId);
    }
}

use Pimphand\GDrive\GoogleDriveStorage;

$storage = GoogleDriveStorage::fromConfig();
$file = $storage->put('photo.jpg', file_get_contents('/path/to/photo.jpg'), 'image/jpeg');



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pimphand\GDrive\Facades\GDrive;

class UploadController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'file' => ['application/octet-stream',
            sizeBytes: (string) $uploaded->getSize(),
        );

        // Save $file['id'] to your application database
        return response()->json([
            'provider_file_id' => $file['id'],
            'name' => $file['name'],
            'mime_type' => $file['mime_type'],
            'size' => $file['size'],
        ], 201);
    }
}

// routes/web.php
use Illuminate\Support\Facades\Route;
use Pimphand\GDrive\Facades\GDrive;
use Pimphand\GDrive\GoogleDriveService;
use Pimphand\GDrive\TokenCrypto;

Route::get('/auth/google', function (GoogleDriveService $drive) {
    $state = TokenCrypto::fromConfig()->randomToken();
    session(['google_oauth_state' => $state]);

    return redirect($drive->getAuthUrl($state));
});

Route::get('/auth/google/callback', function (GoogleDriveService $drive, Request $request) {
    if ($request->query('state') !== session('google_oauth_state')) {
        abort(403, 'Invalid OAuth state.');
    }

    $credentials = $drive->exchangeAuthCode($request->query('code'));

    // Save $credentials to database (use toEncrypted() for encryption)
    $encrypted = $credentials->toEncrypted();

    // ... persist to your ConnectedAccount model

    return redirect('/dashboard')->with('success', 'Google Drive connected.');
});



namespace App\Services;

use App\Models\ConnectedAccount;
use DateTimeInterface;
use Pimphand\GDrive\Contracts\GoogleDriveTokenStore;
use Pimphand\GDrive\GoogleDriveCredentials;

class DatabaseGoogleDriveTokenStore implements GoogleDriveTokenStore
{
    public function __construct(
        private readonly ConnectedAccount $account,
    ) {}

    public function getCredentials(): GoogleDriveCredentials
    {
        return GoogleDriveCredentials::fromEncrypted(
            $this->account->access_token_encrypted,
            $this->account->refresh_token_encrypted,
            $this->account->token_expires_at,
        );
    }

    public function saveAccessToken(string $accessToken, DateTimeInterface $expiresAt): void
    {
        $crypto = app(\Pimphand\GDrive\TokenCrypto::class);

        $this->account->update([
            'access_token_encrypted' => $crypto->encrypt($accessToken),
            'token_expires_at' => $expiresAt,
        ]);
    }
}

use Pimphand\GDrive\GoogleDriveStorage;
use App\Services\DatabaseGoogleDriveTokenStore;

$account = ConnectedAccount::findOrFail($id);
$storage = GoogleDriveStorage::fromConfig(new DatabaseGoogleDriveTokenStore($account));

$file = $storage->put('backup.zip', fopen('php://input', 'r'), 'application/zip');

use Pimphand\GDrive\Contracts\GoogleDriveTokenStore;
use App\Services\DatabaseGoogleDriveTokenStore;

// config/gdrive.php
'token_store' => DatabaseGoogleDriveTokenStore::class,

use Pimphand\GDrive\Facades\GDrive;

// Fetch local records from database, keyed by provider_file_id
$existing = File::where('user_id', $userId)
    ->get()
    ->keyBy('provider_file_id')
    ->map(fn ($f) => [
        'id' => $f->provider_file_id,
        'name' => $f->name,
        'mime_type' => $f->mime_type,
        'size' => (string) $f->size_bytes,
        'status' => $f->status,
    ])
    ->all();

$result = GDrive::drive()->syncAppFolderFiles($existing);

// $result = ['created' => 2, 'updated' => 1, 'deleted' => 0, 'files' => [...]]
foreach ($result['files'] as $change) {
    match ($change['action']) {
        'create' => File::create([...]),
        'update' => File::where('provider_file_id', $change['id'])->update([...]),
        'delete' => File::where('provider_file_id', $change['id'])->update(['status' => 'deleted']),
    };
}
bash
php artisan vendor:publish --tag=gdrive-config
bash
php artisan vendor:publish --tag=gdrive-example
bash
php artisan serve
bash
php artisan gdrive:seed-config

# Show encrypted values (for database seeding)
php artisan gdrive:seed-config --show-encrypted
bash
php artisan gdrive:sync