faiznurullah / google-drive-php
A PHP library for Google Drive integration with Laravel-like API
Requires
- php: ^8.1
- google/apiclient: ^2.18
Requires (Dev)
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2025-06-28 17:27:16 UTC
README
A simple and powerful PHP library for interacting with Google Drive API. This library provides an intuitive interface for managing files and folders in Google Drive with comprehensive examples and real-world usage patterns.
โจ Features
- ๐ Simple & Intuitive API - Easy-to-use methods for all Google Drive operations
- ๐ Complete File Management - Upload, download, move, delete files and folders
- ๐ Real-world Examples - Comprehensive examples for every operation
- ๐ Flexible Authentication - Support for access tokens, refresh tokens, and environment variables
- โ Production Ready - Error handling, retry logic, and robust file operations
- ๐งช Tested & Verified - All examples tested and working
- ๐ Well Documented - Clear documentation with working code samples
๐ Requirements
- PHP 7.4 or higher
- Google Drive API credentials
- Composer for dependency management
๐ Installation
# Clone or download this library git clone https://github.com/faiznurullah/google-drive-php.git cd google-drive-php # Install dependencies composer install
โ๏ธ Setup
1. Get Google Drive API Credentials
- Go to Google Cloud Console
- Create or select a project
- Enable Google Drive API
- Create OAuth 2.0 credentials
- Get your Client ID, Client Secret, and Refresh Token
2. Configure Environment Variables
Create a .env
file in the root directory:
# Required credentials GOOGLE_DRIVE_CLIENT_ID=your-client-id.apps.googleusercontent.com GOOGLE_DRIVE_CLIENT_SECRET=your-client-secret # For automatic token refresh GOOGLE_DRIVE_REFRESH_TOKEN=your-refresh-token # Current access token (will be refreshed automatically) GOOGLE_DRIVE_ACCESS_TOKEN=your-access-token
๐ก Need help getting tokens? Use Google OAuth 2.0 Playground with your credentials.
3. Quick Test
# Test your credentials and basic operations
php quick_start.php
๐ Basic Usage
Using SimpleDrive Helper Class
<?php require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/src/SimpleDrive.php'; // Load environment variables if (file_exists(__DIR__ . '/.env')) { $env = parse_ini_file(__DIR__ . '/.env'); foreach ($env as $key => $value) { putenv("$key=$value"); } } use GoogleDrivePHP\SimpleDrive; // Initialize from environment $drive = SimpleDrive::fromEnv(); // Upload file $fileId = $drive->put('test.txt', 'Hello World!'); echo "Uploaded: $fileId\n"; // Download file $content = $drive->get('test.txt'); echo "Downloaded: $content\n"; // List files $files = $drive->files(); foreach ($files as $file) { echo "- " . $file['name'] . " (" . $file['id'] . ")\n"; } // Check if file exists if ($drive->exists('test.txt')) { echo "File exists!\n"; } // Delete file $drive->delete('test.txt'); echo "File deleted\n";
Direct Google API Usage
<?php require_once __DIR__ . '/vendor/autoload.php'; // Load environment variables if (file_exists(__DIR__ . '/.env')) { $env = parse_ini_file(__DIR__ . '/.env'); foreach ($env as $key => $value) { putenv("$key=$value"); } } // Initialize Google Drive $client = new Google\Client(); $client->setClientId(getenv('GOOGLE_DRIVE_CLIENT_ID')); $client->setClientSecret(getenv('GOOGLE_DRIVE_CLIENT_SECRET')); $client->setAccessToken(getenv('GOOGLE_DRIVE_ACCESS_TOKEN')); $service = new Google\Service\Drive($client); // Upload a file $fileMetadata = new Google\Service\Drive\DriveFile(['name' => 'test.txt']); $content = "Hello, Google Drive!"; $file = $service->files->create($fileMetadata, [ 'data' => $content, 'mimeType' => 'text/plain', 'uploadType' => 'multipart' ]); echo "File uploaded with ID: " . $file->getId() . "\n";
๐ฏ Complete Examples Collection
This library includes comprehensive examples for all operations:
๐ Quick Start
# Test all basic operations
php quick_start.php
What it does:
- โ Tests credentials
- โ Uploads a test file
- โ Lists files in your Drive
- โ Downloads the file
- โ Verifies content
- โ Cleans up test files
๐ Interactive Examples Menu
# Access all examples through interactive menu
php examples/operations/index.php
๐ Individual Operation Examples
1. Upload Operations
php examples/operations/upload_example.php
Features:
- Upload from string content
- Upload from local files
- Upload JSON and CSV data
- Multiple file uploads
- Upload verification
2. Move Operations
php examples/operations/move_example.php
Features:
- Create folders and subfolders
- Move files between folders
- Move folders to other folders
- Upload directly to specific folders
- List folder contents
3. Delete Operations
php examples/operations/delete_example.php
Features:
- Delete individual files
- Backup files before deletion
- Delete multiple files by pattern
- Delete folders recursively
- Safe delete with confirmation
4. Download Operations
php examples/operations/download_example.php
Features:
- Download individual files
- Batch download multiple files
- Download to specific local paths
- Download with progress tracking
- File information retrieval
๐ ๏ธ Core Classes
SimpleDrive
Main helper class for common operations:
$drive = SimpleDrive::fromEnv(); // File operations $fileId = $drive->put($filename, $content); // Upload file $content = $drive->get($filename); // Download file $success = $drive->delete($filename); // Delete file $exists = $drive->exists($filename); // Check if exists $files = $drive->files(); // List all files // Folder operations $folderId = $drive->makeDirectory($folderName); // Create folder
Extended Classes
Examples include extended classes with advanced features:
DriveManager
- Advanced move and folder operationsDriveDeleter
- Safe deletion with backup optionsDriveDownloader
- Batch downloads with progress tracking
๐ง Error Handling
The library includes robust error handling:
try { $content = $drive->get('test.txt'); echo "Downloaded: $content\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; // Handle specific errors if (strpos($e->getMessage(), 'File not found') !== false) { echo "The file doesn't exist\n"; } elseif (strpos($e->getMessage(), 'Unauthorized') !== false) { echo "Check your credentials\n"; } }
๐ Authentication Methods
Method 1: Environment Variables (Recommended)
// Load from .env file automatically $drive = SimpleDrive::fromEnv();
Method 2: Direct Initialization
$drive = new SimpleDrive( clientId: 'your-client-id', clientSecret: 'your-client-secret', refreshToken: 'your-refresh-token', accessToken: 'your-access-token' );
Method 3: Google Client Direct
$client = new Google\Client(); $client->setClientId('your-client-id'); $client->setClientSecret('your-client-secret'); $client->setAccessToken('your-access-token'); $service = new Google\Service\Drive($client);
๐ Testing Your Setup
Basic Credential Test
php test_credentials.php
Quick Operations Test
php quick_start.php
Specific Operation Tests
# Test specific file operations php test_json_data.php # Test delete operation php final_test_new.php # Comprehensive test
๐ Dependencies
This library uses:
google/apiclient
- Google API Client Librarygoogle/apiclient-services
- Google Drive API services- Standard PHP extensions (json, curl, openssl)
Already included via composer.json:
{ "require": { "google/apiclient": "^2.0" } }
๐ฏ Common Use Cases
1. File Backup System
// Backup local files to Google Drive $drive = SimpleDrive::fromEnv(); $localFiles = glob('/path/to/backup/*'); foreach ($localFiles as $file) { $content = file_get_contents($file); $fileId = $drive->put(basename($file), $content); echo "Backed up: " . basename($file) . " (ID: $fileId)\n"; }
2. Data Export to Drive
// Export data as JSON to Google Drive $data = [ 'export_date' => date('Y-m-d H:i:s'), 'records' => fetchDataFromDatabase() ]; $jsonContent = json_encode($data, JSON_PRETTY_PRINT); $fileId = $drive->put('export_' . date('Y-m-d') . '.json', $jsonContent); echo "Data exported with ID: $fileId\n";
3. File Processing Pipeline
// Download, process, and re-upload files $files = $drive->files(); foreach ($files as $file) { if (strpos($file['name'], '.txt') !== false) { // Download file $content = $drive->get($file['name']); // Process content $processedContent = strtoupper($content); // Upload processed version $newName = 'processed_' . $file['name']; $drive->put($newName, $processedContent); echo "Processed: {$file['name']} -> $newName\n"; } }
๐จ Troubleshooting
Common Issues
1. Authentication Errors
Error: Unauthorized / Invalid credentials
Solution:
- Check your Client ID and Client Secret in
.env
- Verify your refresh token is not expired
- Regenerate access token using Google OAuth Playground
2. File Not Found
Error: File not found
Solution:
- Verify file exists in Google Drive using
$drive->files()
- Check file permissions and sharing settings
- Ensure case-sensitive filename matching
3. Permission Denied
Error: The user does not have sufficient permissions
Solution:
- Check API scopes in your Google Cloud Console
- Ensure your OAuth app has Drive API permissions
- Verify you have edit permissions for the file
4. Token Expired
Error: Invalid credentials (access token expired)
Solution:
- Use refresh token for automatic token renewal
- Regenerate tokens from Google OAuth Playground
- Check token expiration time
Getting Fresh Tokens
Use Google OAuth 2.0 Playground:
- Go to https://developers.google.com/oauthplayground
- Select "Drive API v3" scopes
- Authorize with your Google account
- Exchange authorization code for tokens
- Use the refresh token in your
.env
file
Debug Mode
Enable detailed error reporting:
// Enable error reporting error_reporting(E_ALL); ini_set('display_errors', 1); // Test credentials step by step $drive = SimpleDrive::fromEnv(); echo "Connection successful!\n";
๐ File Structure
google-drive-php/
โโโ src/
โ โโโ SimpleDrive.php # Main library class
โโโ examples/
โ โโโ operations/
โ โ โโโ index.php # Interactive menu
โ โ โโโ upload_example.php # Upload operations
โ โ โโโ move_example.php # Move operations
โ โ โโโ delete_example.php # Delete operations
โ โ โโโ download_example.php # Download operations
โ โโโ README.md # Examples documentation
โโโ vendor/ # Composer dependencies
โโโ .env # Your credentials
โโโ composer.json # Dependencies
โโโ quick_start.php # Quick test script
โโโ test_credentials.php # Credential tester
โโโ README.md # This file
๐ License
This library is open-sourced software licensed under the MIT license.
๐ค Contributing
- Fork the repository
- Create a feature branch
- Test your changes with the examples
- Submit a pull request
๐ Support
For issues and questions:
- Check the comprehensive examples in
/examples/operations/
- Review the troubleshooting section above
- Test with the provided test files
- Create an issue with detailed error information
๐ Quick Start Summary
# 1. Install dependencies composer install # 2. Setup .env with your credentials cp .env.example .env # Edit .env with your Google Drive credentials # 3. Test your setup php quick_start.php # 4. Try specific operations php examples/operations/upload_example.php php examples/operations/download_example.php php examples/operations/move_example.php php examples/operations/delete_example.php # 5. Use interactive menu php examples/operations/index.php
๐ฏ Your Google Drive PHP library is ready to use!
For complete examples documentation, see EXAMPLES_COMPLETE.md