Upload to Google Drive From Link Php
In this tutorial, y'all'll acquire Google Drive API and as well List, Create and Upload Files to the bulldoze.
Table Of Contents
- Enable Google Driver API
- Creating a Project in Google Driver API
- Installation and Configure Google Client Library in your project
- Creating Google_Client course
- Generating Admission Token
- Projection File Structure
- Upload File to Bulldoze using HTML form
- Consummate Code
- Listing Root Files and Sub Folders
- Create Folders
- Check Folder Exists
- Insert File to Drive
- Output
- Conclusions
Enable Google Driver API
Enabling the API is the get-go step in creating a simple file upload awarding. Log in to Google and visit
Google Drive – Enable API Key
Creating a Project in Google Driver API
Afterward clicking on Enable the Driver button yous'll see a modal that asks you to give the project a name.
Give Name to Project
Then the adjacent step is to select the fashion through which you will be using this API. Here you select Web Browser as an option.
Select the Fashion
Configure OAuth Client
After the selection of mode, you will be prompted with the Origin URL. You lot will access the drive information through this URL. So, our current URL will be http://localhost.
Configure your Oauth Client
Client Configuration File
In the Final Footstep, y'all volition see a download button that tells y'all to Download Client Configuration. This file is of type JSON format and contains customer ID, client surreptitious, redirect_uris, and javascript_origins.
So download it and salvage information technology in your project root without irresolute its proper name.
Final stride is to download client configuration
Installation and Configure Google Client Library in your project
Open final in your project root and type beneath command. This will install the apiclient into your project.
composer require google/apiclient:^2.0
PS C:\xampp\htdocs\examples> composer require google/apiclient:^two.0 ./composer.json has been created Loading composer repositories with packet information Updating dependencies (including require-dev) Package operations: 12 installs, 0 updates, 0 removals - Installing psr/http-message (1.0.ane): Loading from cache - Installing guzzlehttp/psr7 (i.2.3): Downloading (100%) - Installing guzzlehttp/promises (v1.3.1): Loading from cache - Installing guzzlehttp/guzzle (6.2.0): Downloading (100%) - Installing phpseclib/phpseclib (two.0.28): Downloading (100%) - Installing psr/log (i.1.three): Downloading (100%) - Installing monolog/monolog (ane.25.4): Downloading (100%) - Installing firebase/php-jwt (v3.0.0): Downloading (100%) - Installing google/apiclient-services (v0.139): Downloading (100%) - Installing psr/enshroud (1.0.1): Downloading (100%) - Installing google/auth (v0.8): Downloading (100%) - Installing google/apiclient (v2.0.0): Downloading (100%) phpseclib/phpseclib suggests installing ext-libsodium (SSH2/SFTP can make utilize of some algorithms provided by the libsodium-php extension.) phpseclib/phpseclib suggests installing ext-mcrypt (Install the Mcrypt extension in social club to speed up a few other cryptographic operations.) phpseclib/phpseclib suggests installing ext-gmp (Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetics operations.) monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server) monolog/monolog suggests installing sentry/scout (Allow sending log messages to a Spotter server) monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server) monolog/monolog suggests installing ruflin/elastica (Let sending log messages to an Rubberband Search server) monolog/monolog suggests installing php-amqplib/php-amqplib (Permit sending log messages to an AMQP server using php-amqplib) monolog/monolog suggests installing ext-amqp (Let sending log letters to an AMQP server (ane.0+ required)) monolog/monolog suggests installing ext-mongo (Permit sending log letters to a MongoDB server) monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages to a MongoDB server via PHP Driver) monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB) monolog/monolog suggests installing rollbar/rollbar (Permit sending log messages to Rollbar) monolog/monolog suggests installing php-console/php-console (Permit sending log messages to Google Chrome) google/apiclient suggests installing tedivm/stash (For caching certs and tokens (using Google_Client::setCache)) Writing lock file Generating autoload files 2 packages you are using are looking for funding. Utilise the `composer fund` command to notice out more!
Creating Google_Client class
The form Google_Client is used for authority of a client and set scopes such as read-simply, file admission, etc.
If y'all want to upload files then your scope must be set to Google_Service_Drive::DRIVE which internally points to URL https://www.googleapis.com/auth/drive.
Hither is how the class looks google-bulldoze.php.
<?php require __DIR__ . '/vendor/autoload.php'; /** * Returns an authorized API client. * @return Google_Client the authorized customer object */ role getClient() { $customer = new Google_Client(); $customer->setApplicationName('Google Drive API PHP Quickstart'); $client->setRedirectUri('http://localhost/test-examples/php/google-bulldoze-api/oauth2callback.php'); $client->setScopes(Google_Service_Drive::DRIVE); $client->setAuthConfig('credentials.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); // Load previously authorized token from a file, if information technology exists. // The file token.json stores the user'southward access and refresh tokens, and is // created automatically when the authorization menstruation completes for the first // time. $tokenPath = 'token.json'; if (file_exists($tokenPath)) { $accessToken = json_decode(file_get_contents($tokenPath), truthful); $client->setAccessToken($accessToken); } // If there is no previous token or information technology's expired. if ($customer->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($customer->getRefreshToken()); } else { // Asking authorization from the user. $authUrl = $customer->createAuthUrl(); printf("Open the post-obit link in your browser:\n%southward\n", $authUrl); impress 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization lawmaking for an admission token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken); // Check to see if in that location was an mistake. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } // Salvage the token to a file. if (!file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, true); } file_put_contents($tokenPath, json_encode($client->getAccessToken())); } return $client; } // Get the API client and construct the service object. $client = getClient(); In order to access the files from the cloud, you have to create a verification lawmaking.
Generating Access Token
Become to the root project and open terminal and type below command.
php google-drive.php
This volition brandish a URL when clicked open in your browser and asks you lot to log in and authorize this request. After client hallmark, you will be prompted with verification lawmaking and you have to paste information technology here.
Udemy PHP Class
Project File Construction
Your-Project |-- uploads |-- vendor |-- composer.json |-- composer.lock |-- credentials.json //contains google client credentials |-- form.php // HTML class to upload files |-- google-drive.php // contains instance of API customer |-- oauth2callback.php // Merely a php page that used for redirect uri and too contains verification code |-- submit.php // here go our master business logic of listing, creating and uploading files. |-- token.json // OAuth token this is generated automatically one time you enter verification code.
Upload File to Drive using HTML form
Let'south try to upload a file into google bulldoze using the class method.
form.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-viii"> <meta proper name="viewport" content="width=device-width, initial-calibration=i.0"> <title>File Upload</title> </head> <body> <h2>PHP Google Drive Api </h2> <a href="submit.php?list_files_and_folders=1">Click hither to list all files and folders</a> <h2>File Upload</h2> <form action="submit.php" method="post" enctype="multipart/course-data" > <label for="">Cull File</label> <input type="file" name="file" > <input type="submit" proper noun="submit" value="submit" > </class> </body> </html>
submit.php
Backend code for file upload.
<?php error_reporting(E_ERROR | E_PARSE); crave __DIR__ . '/google-drive.php'; if( isset( $_POST['submit'] ) ){ if( empty( $_FILES["file"]['tmp_name'] ) ){ echo "Go back and Select file to upload."; exit; } $file_tmp = $_FILES["file"]["tmp_name"]; $file_type = $_FILES["file"]["type"]; $file_name = basename($_FILES["file"]["name"]); $path = "uploads/".$file_name; move_uploaded_file($file_tmp, $path); $folder_id = create_folder( "google-drive-test-binder" ); $success = insert_file_to_drive( $path , $file_name, $folder_id); if( $success ){ echo "file uploaded successfully"; } else { echo "Something went wrong."; } } // This will create a folder and also sub folder when $parent_folder_id is given office create_folder( $folder_name, $parent_folder_id=zero ){ $folder_list = check_folder_exists( $folder_name ); // if folder does not exists if( count( $folder_list ) == 0 ){ $service = new Google_Service_Drive( $GLOBALS['client'] ); $folder = new Google_Service_Drive_DriveFile(); $folder->setName( $folder_name ); $folder->setMimeType('application/vnd.google-apps.folder'); if( !empty( $parent_folder_id ) ){ $folder->setParents( [ $parent_folder_id ] ); } $issue = $service->files->create( $folder ); $folder_id = zippo; if( isset( $result['id'] ) && !empty( $event['id'] ) ){ $folder_id = $result['id']; } render $folder_id; } return $folder_list[0]['id']; } // This will check folders and sub folders by name office check_folder_exists( $folder_name ){ $service = new Google_Service_Drive($GLOBALS['client']); $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and trashed=false"; $files = $service->files->listFiles($parameters); $op = []; foreach( $files as $thou => $file ){ $op[] = $file; } return $op; } // This will display listing of folders and direct child folders and files. function get_files_and_folders(){ $service = new Google_Service_Drive($GLOBALS['customer']); $parameters['q'] = "mimeType='application/vnd.google-apps.folder' and 'root' in parents and trashed=false"; $files = $service->files->listFiles($parameters); repeat "<ul>"; foreach( $files as $thousand => $file ){ echo "<li> {$file['name']} - {$file['id']} ---- ".$file['mimeType']; attempt { // subfiles $sub_files = $service->files->listFiles(array('q' => "'{$file['id']}' in parents")); repeat "<ul>"; foreach( $sub_files every bit $kk => $sub_file ) { echo "<li> {$sub_file['proper noun']} - {$sub_file['id']} ---- ". $sub_file['mimeType'] ." </li>"; } echo "</ul>"; } catch (\Throwable $th) { // dd($th); } echo "</li>"; } echo "</ul>"; } // This will insert file into drive and returns boolean values. role insert_file_to_drive( $file_path, $file_name, $parent_file_id = zero ){ $service = new Google_Service_Drive( $GLOBALS['client'] ); $file = new Google_Service_Drive_DriveFile(); $file->setName( $file_name ); if( !empty( $parent_file_id ) ){ $file->setParents( [ $parent_file_id ] ); } $result = $service->files->create( $file, assortment( 'data' => file_get_contents($file_path), 'mimeType' => 'application/octet-stream', ) ); $is_success = false; if( isset( $result['name'] ) && !empty( $consequence['name'] ) ){ $is_success = true; } return $is_success; } if( isset( $_GET['list_files_and_folders'] ) ){ repeat "<h1>Retriving List all files and folders from Google Drive</h1>"; get_files_and_folders(); } // Function just for easier debugging function dd( ...$d ){ echo "<pre style='background-colour:#000;color:#fff;' >"; print_r($d); go out; } In oauth2callback.php
<?php echo "<pre>"; print_r($_GET);
Functions and their purpose.
- getClient(): This role returns authorized customer object.
- create_folder(): Creates binder or subfolder
- check_folder_exists(): Before creating checks wheather folder exists using query terms.
- insert_file_to_drive(): Inserts file into drive and returns boolean value
truthfulon success andfakeon failure. - get_files_and_folders(): Retrives root binder with files with their direct childrens.
- dd(): This role is used to brand debugging easier.
Output
Useful Links
- Google Drive PHP Quickstart
- Google Developers Console
Conclusion
In conclusion, we have come to end on our post on PHP Google Drive API | Listing, Create, and Upload Files. For any suggestions annotate below.
Summary
Reviewer The Code Learners
Review Engagement
Reviewed Item
PHP Google Drive API | List, Create Folders, Sub Folders and Upload Files
Author Rating
Software Name Google Drive API Software Name Windows Os, Mac Os and Ubuntu Bone Software Category PHP API Development
Source: https://thecodelearners.com/php-google-drive-api-list-create-folders-sub-folders-and-upload-files/
0 Response to "Upload to Google Drive From Link Php"
Post a Comment