PHPackages                             open-php/google-drive-uploader - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. open-php/google-drive-uploader

ActiveLibrary[File &amp; Storage](/categories/file-storage)

open-php/google-drive-uploader
==============================

A robust, self-healing Google Drive Uploader for PHP. Features automatic token lifecycle management, smart folder handling, and reliable helpers for embedding images and videos.

1.0.13(3mo ago)07MITPHPPHP &gt;=7.4

Since Jan 15Pushed 3mo agoCompare

[ Source](https://github.com/mrsandipmandal/google-drive-uploader)[ Packagist](https://packagist.org/packages/open-php/google-drive-uploader)[ Docs](https://github.com/mrsandipmandal/google-drive-uploader)[ RSS](/packages/open-php-google-drive-uploader/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (15)Used By (0)

Google Drive Uploader Library
=============================

[](#google-drive-uploader-library)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4f17f2ed745fd736bd5b42884ab17e5b1e7d60511a9ce5e542a83bd8e254bbba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f70656e2d7068702f676f6f676c652d64726976652d75706c6f616465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/open-php/google-drive-uploader)[![Total Downloads](https://camo.githubusercontent.com/af9bec148ef7d094b5bab29c71d129bfdb8b1a1fbd6520b5ea021ff3c90c9726/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f70656e2d7068702f676f6f676c652d64726976652d75706c6f616465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/open-php/google-drive-uploader)[![License](https://camo.githubusercontent.com/3d5da84cb1aef81734c3191959001bafdea109a407d93e0c2cf5f0d7c575d33f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f70656e2d7068702f676f6f676c652d64726976652d75706c6f616465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/open-php/google-drive-uploader)

A simple, robust PHP library for uploading files to Google Drive. It handles creating folders, setting public permissions, and most importantly, **automatic token refreshing and retries** (self-healing auth) to handle the dreaded 7-day token expiry for testing apps.

Features
--------

[](#features)

- 📂 **Auto-create folders**: Automatically creates folders if they don't exist.
- 🔄 **Self-Healing Auth**: Automatically catches 401 errors, refreshes tokens using your refresh token, and retries the upload.
- 🌍 **Public Links**: Option to automatically make uploaded files public and get a web-viewable link.
- 📦 **PSR-4 Compliant**: Namespace `Open\GoogleDrive`, ready for any Composer project.

Installation
------------

[](#installation)

Install via Composer:

```
composer require open-php/google-drive-uploader
```

Google Cloud Setup
------------------

[](#google-cloud-setup)

To use this library, you need credentials from the Google Cloud Console.

1. Go to [Google Cloud Console](https://console.cloud.google.com/).
2. Create a Project.
3. Enable **Google Drive API**.
4. Go to **Credentials** -&gt; **Create Credentials** -&gt; **OAuth Client ID**.
5. Application Type: **Web Application**.
6. Redirect URI: `http://localhost/callback.php` (or your production URL).
7. Download the JSON and save it as `credentials.json`.
8. **Important**: If your app is in "Testing" mode, tokens expire in 7 days. Ideally, set Publishing Status to **"In Production"** to avoid this, but this library handles auto-refresh if valid refresh tokens are present.

Usage
-----

[](#usage)

### 1. Initialization

[](#1-initialization)

```
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);
```

### 2. First-Time Authentication

[](#2-first-time-authentication)

If you don't have a `token.json` yet, you need to authorize the app.

```
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
}
```

### 3. Uploading a File

[](#3-uploading-a-file)

```
try {
    $localFilePath = '/path/to/image.jpg';
    $folderName = 'My Uploads';

    // Upload file
    $fileId = $drive->uploadFile($localFilePath, $folderName);

    // Get public accessible link (if enabled in service)
    // Note: ensure uploadFile returns the file object or ID based on your specific version needs
    // The current implementation returns a Google_Service_Drive_DriveFile object

    echo "File Uploaded! ID: " . $fileId->id . "\n";
    echo "Web View Link: " . $fileId->getWebViewLink() . "\n";

    // For images (), use the embed link:
    echo "Embed Link: " . $drive->getEmbedLink($fileId->id);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

### 4. Uploading Multiple Files

[](#4-uploading-multiple-files)

To upload efficiently (checking folder existence only once):

```
$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";
}
```

### 5. Deleting a File

[](#5-deleting-a-file)

You can permanently delete a file using its File ID:

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

### 6. Renaming a File

[](#6-renaming-a-file)

You can rename a file using its File ID:

```
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();
}
```

Laravel Integration
-------------------

[](#laravel-integration)

This package is framework-agnostic, but can be easily used in Laravel. This package handles the entire OAuth flow. Here is a complete production-ready implementation.

### 1. Define Routes

[](#1-define-routes)

In `routes/web.php`:

```
use App\Http\Controllers\DriveController;

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

Important

**Google Cloud Console Setup**You MUST add the full callback URL to your **Authorized redirect URIs** in the Google Cloud Console.

If your app runs at `http://localhost:8000`, add: `http://localhost:8000/google/callback`

If your app runs at `http://localhost/myapp/public`, add: `http://localhost/myapp/public/google/callback`

**The URL must match EXACTLY what your Laravel app generates.**

### 2. The Controller

[](#2-the-controller)

```
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' => 'required|file']);

        try {
            $drive = $this->getDriveService();

            $uploadedFile = $request->file('file');

            $googleFile = $drive->uploadFile(
                $uploadedFile->getPathname(),
                'LaravelUploads',
                true,
                $uploadedFile->getClientOriginalName()
            );

            return response()->json([
                'status' => 'success',
                'url' => $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.";
    }
}
```

How to Display Files (Blade Example)
------------------------------------

[](#how-to-display-files-blade-example)

Different file types require different HTML tags.

**Controller:** Pass the `id` and `mimeType` to your view.

```
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
]);
```

**View (`googleFileView.blade.php`):**

```

@if(str_contains($mimeType, 'image/'))

@elseif(str_contains($mimeType, 'video/'))

@elseif($mimeType == 'application/pdf')

@else
    Download File
@endif
```

Support
-------

[](#support)

- **Issues**: [GitHub Issues](https://github.com/mrsandipmandal/google-drive-uploader/issues)
- **Source**: [GitHub Repository](https://github.com/mrsandipmandal/google-drive-uploader)

License
-------

[](#license)

This project is licensed under the MIT License. See [LICENSE](LICENSE) file for details.

Author
------

[](#author)

- **Sandip Mandal** - [GitHub](https://github.com/mrsandipmandal)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance81

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

14

Last Release

102d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cfba1cdaaab95e40cfe363c3cd258c77ab78c5bf3fc26112e4b7a8d971565b5?d=identicon)[mrsandipmandal](/maintainers/mrsandipmandal)

---

Top Contributors

[![mrsandipmandal](https://avatars.githubusercontent.com/u/75414705?v=4)](https://github.com/mrsandipmandal "mrsandipmandal (22 commits)")

---

Tags

phplaraveloauth2google apigoogle-drivecloud-storagegoogle-drive-apiauto-refreshdrive upload

### Embed Badge

![Health badge](/badges/open-php-google-drive-uploader/health.svg)

```
[![Health](https://phpackages.com/badges/open-php-google-drive-uploader/health.svg)](https://phpackages.com/packages/open-php-google-drive-uploader)
```

###  Alternatives

[masbug/flysystem-google-drive-ext

Flysystem adapter for Google Drive with seamless virtual&lt;=&gt;display path translation

2631.7M14](/packages/masbug-flysystem-google-drive-ext)[madnest/madzipper

Easier zip file handling for Laravel applications.

1382.3M6](/packages/madnest-madzipper)[sopamo/laravel-filepond

Laravel backend module for filepond uploads

215272.2k3](/packages/sopamo-laravel-filepond)[soarecostin/file-vault

192195.0k](/packages/soarecostin-file-vault)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
