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
}
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
]);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.