Uploading File in Google Drive using Google Drive API and PHP Tutorial

In this tutorial, you will learn to Upload Files into Google Drive using PHP Language and Google Drive API without using any PHP Library. The main purpose of this tutorial is to provide IT/CS Students and new programmers with a reference for learning how to integrate Google APIs into PHP. Here, a step-by-step tutorial for setting up a project in Google Cloud Console is provided with snippets for achieving this tutorial goal. A sample source code that demonstrates the integration of the said platform and language is provided and is free to download.

What is Google Drive API?

The Google Drive API helps you to develop apps that make use of Google Drive cloud storage. You can use the Drive API to build applications that interface with Drive and have strong functionality.

How to Upload Files in Google Drive using PHP?

Since this tutorial will teach us to upload files in Google Drive using PHP without any PHP Library, we can use PHP's built-in cURL methods to execute HTTP Requests for Uploading Files. using the Google Drive APIs oAuth Client ID and Secret Key, the platform will allow our PHP application to manage files for logged-in users.

Steps for Implementing File Uploads in Google Drive using PHP?

  1. Create a New Project in Google Cloud Console
  2. Enable Google Drive API for your created project.
  3. Create an OAuth Client ID
  4. Create an OAuth Consent Screen
  5. Implement Google Authentication into your web application to generate an access token
  6. Create the Upload Script using PHP using the API's provided URIs and request formats.

Setting up Google Cloud Console.

Go to Google Cloud Console.

Creating Project

Step 1:

On the Google Cloud Console home page, click the project dropdown located at the left side of the search box. Then, a popup modal will be shown, and click the New Project button/anchor located at the top-right side of the modal.

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

Step 2:

Next, is to fill in all the required fields for creating a new project in Google Cloud Console. Check out the images below.

PHP and Google Drive Integration Setup

Setting up Google Drive API

Step 1:

After the successful creation of the project, select the project you created and navigate the page to the Project Dashboard.

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

Step 2:

Next, search the Google Drive API in the search box. Then, navigate the page to the API page to enable it.

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

Setting up Google Drive API OAuth Consent Screen

Step 1:

Select the APIs & Services on the menu bar.

Step 2:

Next, navigate the page to OAuth Consent Screen.

PHP and Google Drive Integration Setup

Step 3:

Then, fill in all the required fields like the images shown below.

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

PHP and Google Drive Integration Setup

Setting up Google Drive API Credentials

Step 1:

Navigate your page to the Credentials Page

PHP and Google Drive Integration Setup

Step 2:

Next, click the Create Credentials and choose OAuth client ID

PHP and Google Drive Integration Setup

Step 3:

Next, fill in all the required fields on the form like the image below.

PHP and Google Drive Integration Setup

Step 4:

Copy and save the generated Client ID and Secret Key for later use.

PHP and Google Drive Integration Setup

Let's start with the Coding Part

In your source code directory, create a new file named config.php. This is a PHP file that contains the constants that are needed for the simple application that we will create. Make sure to change GCLIENT_ID and GCLIENT_SECRET defined constants with the generated ones from your OAuth client ID creation.

  1. <?php
  2. // Define Google Client Credentials, Scopes, and URIs
  3. define('GCLIENT_ID', "Your Client ID Here");
  4. define('GCLIENT_SECRET', "Your Client Secret Here");
  5. define('GCLIENT_SCOPE', "https://www.googleapis.com/auth/drive");
  6. define('GCLIENT_REDIRECT', "https://localhost/php-gdrive-upload/index.php");
  7.  
  8. define('OAUTH2_TOKEN_URI',"https://oauth2.googleapis.com/token");
  9.  
  10. define('DRIVE_FILE_UPLOAD_URI',"https://www.googleapis.com/upload/drive/v3/files");
  11. define('DRIVE_FILE_META_URI',"https://www.googleapis.com/drive/v3/files/");
  12.  
  13.  
  14. // Authentication URL
  15. $gOauthURL = "https://accounts.google.com/o/oauth2/auth?scope=".(urldecode(GCLIENT_SCOPE))."&redirect_uri=".(urlencode(GCLIENT_REDIRECT))."&client_id=".(urlencode(GCLIENT_ID))."&access_type=online&response_type=code";
  16.  
  17. if(isset($_GET['code'])){
  18.     $_SESSION['code'] = $_GET['code'];
  19.     require_once("GoogleDriveUploadAPI.php");
  20.     $gdriveAPI = new GoogleDriveUploadAPI();
  21.     // Save Access Token
  22.     $_SESSION['access_token'] = $gdriveAPI->GetAccessToken()['access_token'];
  23.     header('location:./');
  24. }
  25. // if(!isset($_SESSION['code']))
  26. // header("location:{$gOauthURL}");

Next, let's create the PHP Class file that contains the script for getting an access token, uploading the file to Google Drive, and Updating the File Meta. Save this file as GoogleDriveUploadAPI.php

  1. <?php
  2.  
  3. class GoogleDriveUploadAPI{
  4.     function __construct(){
  5.        
  6.     }
  7.     public function GetAccessToken() {
  8.         $curlPost = 'client_id='.GCLIENT_ID.'&redirect_uri=' .GCLIENT_REDIRECT. '&client_secret=' . GCLIENT_SECRET . '&code='. $_SESSION['code'] . '&grant_type=authorization_code';
  9.         $ch = curl_init();        
  10.         curl_setopt($ch, CURLOPT_URL, OAUTH2_TOKEN_URI);        
  11.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
  12.         curl_setopt($ch, CURLOPT_POST, 1);        
  13.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  14.         curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);    
  15.         $data = json_decode(curl_exec($ch), true);
  16.         $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  17.            
  18.         if ($http_code != 200) {
  19.             $error_msg = 'Failed to receieve access token';
  20.             if (curl_errno($ch)) {
  21.                 $error_msg = curl_error($ch);
  22.             }
  23.             print_r($data);
  24.             throw new Exception('Error '.$http_code.': '.$error_msg);
  25.         }
  26.                
  27.         return $data;
  28.     }
  29.     public function toDrive($FileContents, $MimeType) {
  30.         $API_URL = DRIVE_FILE_UPLOAD_URI . '?uploadType=media';
  31.            
  32.         $ch = curl_init();        
  33.         curl_setopt($ch, CURLOPT_URL, $API_URL);        
  34.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
  35.         curl_setopt($ch, CURLOPT_POST, 1);        
  36.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  37.         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: '.$MimeType, 'Authorization: Bearer '. $_SESSION['access_token']));
  38.         curl_setopt($ch, CURLOPT_POSTFIELDS, $FileContents);
  39.         $data = json_decode(curl_exec($ch), true);
  40.         $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);        
  41.            
  42.         if ($http_code != 200) {
  43.             $error_msg = 'Failed to upload file to Google Drive';
  44.             if (curl_errno($ch)) {
  45.                 $error_msg = curl_error($ch);
  46.             }
  47.             throw new Exception('Error '.$http_code.': '.$error_msg);
  48.         }
  49.    
  50.         return $data['id'];
  51.     }
  52.     public function FileMeta($FileID, $FileMetaData) {
  53.         $API_URL = DRIVE_FILE_META_URI . $FileID;
  54.            
  55.         $ch = curl_init();        
  56.         curl_setopt($ch, CURLOPT_URL, $API_URL);        
  57.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
  58.         curl_setopt($ch, CURLOPT_POST, 1);        
  59.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  60.         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '. $_SESSION['access_token']));
  61.         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
  62.         curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($FileMetaData));
  63.         $data = json_decode(curl_exec($ch), true);
  64.         $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);        
  65.            
  66.         if ($http_code != 200) {
  67.             $error_msg = 'Failed to update file metadata';
  68.             if (curl_errno($ch)) {
  69.                 $error_msg = curl_error($ch);
  70.             }
  71.             print_r($data);
  72.             throw new Exception('Error '.$http_code.': '.$error_msg);
  73.         }
  74.    
  75.         return $data;
  76.     }
  77. }

Next, we will create the script for the interface of the application. The below script is a combined PHP and HTML script that contains the elements of the upload form and Google Login Button. Save this file as index.php

  1. <?php
  2. require_once('config.php');
  3. ?>
  4. <!DOCTYPE html>
  5. <html lang="en">
  6.     <meta charset="UTF-8">
  7.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9.     <title>PHP - Upload File in Gdrive</title>
  10.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  11.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  12.     <link rel="stylesheet" href="assets/css/styles.css">
  13.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  14.     <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  15.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  16.  
  17.     <script src="assets/js/script.js"></script>
  18. </head>
  19.     <main>
  20.         <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  21.             <div class="container">
  22.                 <a class="navbar-brand" href="./">Upload File in Gdrive - PHP</a>
  23.                
  24.                 <div>
  25.                     <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26.                 </div>
  27.             </div>
  28.         </nav>
  29.         <div id="main-wrapper">
  30.             <div class="container px-5 my-3" >
  31.                 <script>
  32.                     start_loader()
  33.                 </script>
  34.                 <div class="mx-auto col-lg-10 col-md-12 col-sm-12 col-xs-12">
  35.                     <?php if(isset($_SESSION['access_token']) && !empty($_SESSION['access_token'])): ?>
  36.                         <div class="card rounded-0 shadow">
  37.                             <div class="card-header rounded-0">
  38.                                 <div class="card-title"><b>Upload Form</b></div>
  39.                             </div>
  40.                             <div class="card-body rounded-0">
  41.                                 <div class="container-fluid">
  42.                                     <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data">
  43.                                         <div class="mb-3">
  44.                                             <label for="file" class="form-label">Upload</label>
  45.                                             <input class="form-control" type="file" name="file" id="file" accept=".tar,.gz,.zip" required>
  46.                                         </div>
  47.                                     </form>
  48.                                 </div>
  49.                             </div>
  50.                             <div class="card-footer rounded-0">
  51.                                 <button class="btn btn-primary rounded-0" form="upload-form"><i class="fa fa-upload"></i> Upload to Drive</button>
  52.                                 <a class="btn btn-danger rounded-0" href="./logout.php"><i class="fa fa-sign-out"></i> Logout</a>
  53.                             </div>
  54.                         </div>
  55.                     <?php else: ?>
  56.                         <div class="col-lg-3 col-md-5 col-sm-10 col-xs-12 mx-auto">
  57.                             <a class="btn btn-primary rounded-pill w-100" href="<?= $gOauthURL ?>">Sign with Google</a>
  58.                         </div>
  59.                     <?php endif; ?>
  60.                 </div>
  61.             </div>
  62.         </div>
  63.         <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
  64.             <div class="">
  65.                 <div class="text-center">
  66.                     All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">Upload File in Gdrivep - PHP</span>
  67.                 </div>
  68.                 <div class="text-center">
  69.                     <a href="mailto:[email protected]" class="text-decoration-none text-success">[email protected]</a>
  70.                 </div>
  71.             </div>
  72.         </footer>
  73.     </main>
  74. </body>
  75. </html>

Next, create the PHP script for uploading the selected file. In the script below, you can see that the file will be temporarily uploaded to the server at the assets/temp directories and will be deleted after the successful/unsuccessful uploading to google drive. So make sure that the said directory is also existing in your source code folder. Save the file below as upload.php.

  1. <?php
  2. require_once("config.php");
  3. require_once("GoogleDriveUploadAPI.php");
  4. $gdriveAPI = new GoogleDriveUploadAPI();
  5.  
  6. if(isset($_FILES) && !empty($_FILES['file']['tmp_name'])){
  7.     $fname = $_FILES['file']['name'];
  8.     // temporarily save the file
  9.     $upload = move_uploaded_file($_FILES['file']['tmp_name'], 'assets/temp/'.$fname);
  10.     if($upload){
  11.         $access_token = $_SESSION['access_token'];
  12.         $error="";
  13.         if(!empty($access_token)){
  14.             // identify the file mime type
  15.             $mimeType = mime_content_type("assets/temp/".$_FILES['file']['name']);
  16.             // get the file contents
  17.             $FileContents =  file_get_contents("assets/temp/".$_FILES['file']['name']);
  18.            
  19.             // Upload File to Google Drive
  20.             $gDriveFID = $gdriveAPI->toDrive($FileContents, $mimeType);
  21.             if($gDriveFID){
  22.                 // Rename Uploaded file
  23.                 $meta = [ "name" => $_FILES['file']['name'] ];
  24.                 // Update Meta Revision
  25.                 $gDriveMeta = $gdriveAPI->FileMeta($gDriveFID, $meta);
  26.                 if($gDriveMeta){
  27.                     unlink('assets/temp/'.$fname);
  28.                     echo "<script> alert('File has been uploaded.');location.replace('./'); </script>";
  29.                 }else{
  30.                     $error = "Fail to Update the File Meta in Google Drive.";
  31.                 }
  32.             }else{
  33.                 $error = "File Uploading failed in Google Drive.";
  34.             }
  35.         }else{
  36.             $error = "File Uploading failed in Google Drive due to invalid access token.";
  37.         }
  38.         unlink('assets/temp/'.$fname);
  39.         echo "<script> alert('File has failed to upload in Google Drive. Error: '.$error);location.replace('./'); </script>";
  40.     }else{
  41.         throw new ErrorException("File has failed to upload due to unknown reason.");
  42.     }
  43.    
  44.  
  45. }else{
  46.     throw new ErrorException("No Files has been sent.");
  47. }
  48.  
  49. ?>

Lastly, create the logout script for the application to allow the user to log out of their Google Account from the application. Save the file below as logout.php.

  1. <?php
  2. foreach($_SESSION as $k => $v){
  3.     unset($_SESSION[$k]);
  4. }
  5. header('location:./');

Snapshot

Here's the snapshot of the interface of the application I provided above.

PHP and Google Drive Integration Setup

That's it! You can now test the sample application on your side and see if it works properly. Please make sure that you are only using the google accounts listed on OAuth Consent Screen Test Users.

I also provided the source code zip file that I created for this tutorial which is free to download. You can download it by clicking the Download Button located after this article's content.

That's the end of this tutorial. I hope this Uploading File in Google Drive using PHP and Google Drive API Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Comments

Thank you for the detailed explanation and codes the code worked. I have a question: When I started to upload the first file, my google drive account asked for approval for the file from the xxx.com site, I gave approval and uploaded. On the website, I want to send google drive automatically when the database is backed up, but how do I need to confirm for the website?

Add new comment