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?
- Create a New Project in Google Cloud Console
- Enable Google Drive API for your created project.
- Create an OAuth Client ID
- Create an OAuth Consent Screen
- Implement Google Authentication into your web application to generate an access token
- 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.
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.
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.
Step 2:
Next, search the Google Drive API in the search box. Then, navigate the page to the API page to enable it.
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.
Step 3:
Then, fill in all the required fields like the images shown below.
Setting up Google Drive API Credentials
Step 1:
Navigate your page to the Credentials Page
Step 2:
Next, click the Create Credentials and choose OAuth client ID
Step 3:
Next, fill in all the required fields on the form like the image below.
Step 4:
Copy and save the generated Client ID and Secret Key for later use.
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.
- <?php
- // Define Google Client Credentials, Scopes, and URIs
- // Authentication URL
- $_SESSION['code'] = $_GET['code'];
- require_once("GoogleDriveUploadAPI.php");
- $gdriveAPI = new GoogleDriveUploadAPI();
- // Save Access Token
- $_SESSION['access_token'] = $gdriveAPI->GetAccessToken()['access_token'];
- }
- // if(!isset($_SESSION['code']))
- // 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
- <?php
- class GoogleDriveUploadAPI{
- function __construct(){
- }
- public function GetAccessToken() {
- $curlPost = 'client_id='.GCLIENT_ID.'&redirect_uri=' .GCLIENT_REDIRECT. '&client_secret=' . GCLIENT_SECRET . '&code='. $_SESSION['code'] . '&grant_type=authorization_code';
- if ($http_code != 200) {
- $error_msg = 'Failed to receieve access token';
- }
- throw new Exception('Error '.$http_code.': '.$error_msg);
- }
- return $data;
- }
- public function toDrive($FileContents, $MimeType) {
- $API_URL = DRIVE_FILE_UPLOAD_URI . '?uploadType=media';
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: '.$MimeType, 'Authorization: Bearer '. $_SESSION['access_token']));
- if ($http_code != 200) {
- $error_msg = 'Failed to upload file to Google Drive';
- }
- throw new Exception('Error '.$http_code.': '.$error_msg);
- }
- return $data['id'];
- }
- public function FileMeta($FileID, $FileMetaData) {
- $API_URL = DRIVE_FILE_META_URI . $FileID;
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '. $_SESSION['access_token']));
- if ($http_code != 200) {
- $error_msg = 'Failed to update file metadata';
- }
- throw new Exception('Error '.$http_code.': '.$error_msg);
- }
- return $data;
- }
- }
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
- <?php
- require_once('config.php');
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <link rel="stylesheet" href="assets/css/styles.css">
- <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>
- </head>
- <body>
- <main>
- <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div id="main-wrapper">
- <div class="container px-5 my-3" >
- <script>
- start_loader()
- </script>
- <div class="mx-auto col-lg-10 col-md-12 col-sm-12 col-xs-12">
- <?php if(isset($_SESSION['access_token']) && !empty($_SESSION['access_token'])): ?>
- <div class="card rounded-0 shadow">
- <div class="card-header rounded-0">
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data">
- <div class="mb-3">
- <input class="form-control" type="file" name="file" id="file" accept=".tar,.gz,.zip" required>
- </div>
- </form>
- </div>
- </div>
- <div class="card-footer rounded-0">
- </div>
- </div>
- <?php else: ?>
- <div class="col-lg-3 col-md-5 col-sm-10 col-xs-12 mx-auto">
- </div>
- <?php endif; ?>
- </div>
- </div>
- </div>
- <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
- <div class="">
- <div class="text-center">
- </div>
- <div class="text-center">
- </div>
- </div>
- </footer>
- </main>
- </body>
- </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.
- <?php
- require_once("config.php");
- require_once("GoogleDriveUploadAPI.php");
- $gdriveAPI = new GoogleDriveUploadAPI();
- $fname = $_FILES['file']['name'];
- // temporarily save the file
- if($upload){
- $access_token = $_SESSION['access_token'];
- $error="";
- // identify the file mime type
- // get the file contents
- // Upload File to Google Drive
- $gDriveFID = $gdriveAPI->toDrive($FileContents, $mimeType);
- if($gDriveFID){
- // Rename Uploaded file
- $meta = [ "name" => $_FILES['file']['name'] ];
- // Update Meta Revision
- $gDriveMeta = $gdriveAPI->FileMeta($gDriveFID, $meta);
- if($gDriveMeta){
- echo "<script> alert('File has been uploaded.');location.replace('./'); </script>";
- }else{
- $error = "Fail to Update the File Meta in Google Drive.";
- }
- }else{
- $error = "File Uploading failed in Google Drive.";
- }
- }else{
- $error = "File Uploading failed in Google Drive due to invalid access token.";
- }
- echo "<script> alert('File has failed to upload in Google Drive. Error: '.$error);location.replace('./'); </script>";
- }else{
- throw new ErrorException("File has failed to upload due to unknown reason.");
- }
- }else{
- throw new ErrorException("No Files has been sent.");
- }
- ?>
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.
- <?php
- foreach($_SESSION as $k => $v){
- }
Snapshot
Here's the snapshot of the interface of the application I provided above.
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
How to pre-approve google drive account on behalf of website?
Add new comment
- Add new comment
- 6787 views