Home > PHP > How to Upload Files to Google Drive with PHP?

How to Upload Files to Google Drive with PHP?

In this tutorial, we will learn about how to generate a google client ID and client secret to using upload files to google drive with PHP.

As you know Google Drive is a cloud storage platform that allows us to store files and share them with others. You can sync files on many devices and access them anywhere globally.

We can also upload the files to google drive programmatically using the Drive API. The API allows us to manage files and folders on google drive and it uses to authenticate the request and authorize access.

If you have a web application and you want to implement this functionality, you have to give permission to users to access and manage the google drive files using the Drive REST API services.

Let’s see how to enable Drive API and use it to upload the files to google drive programmatically with php.

Generate Google Client ID and Client Secret

So, first of all, we need a google Client ID and Client Secret from the google developer console dashboard. If you already have then you can use it, make sure you have enabled the Drive API service in it.

If you don’t have the client id and client secret, follow the below steps to create a new project in google console and generate the google client id and client secret.

  • Go to the google developer console and login with your google account.
  • Click on the “Select a Project” option at the top header to see the following image as reference.
    generate maps api create project
  • Now you will see a popup box, so click on the “New Project” button.
    generate maps api create new project
  • It will redirect you to a new page. Enter here your Project name and select an Organization and then click on the “Create” button.
    Google Drive API Project
  • Select the “Library” from the sidebar and find the Google Drive API service and Enable it.
    Google Drive API Service
  • Select the “OAuth Consent Screen” from the sidebar and select the External option and click on Create button.
    configure-consent screen external type external user type
  • Now fill in all the required fields like App name, support email, logo, application homepage, privacy page, etc. And final save the all settings.
    Google App Registration
  • Now create the google app credential by going through “Credential” from the sidebar and then clicking on the OAuth client ID from the dropdown option.
    Create Google App Credential
  • Select application type as “Web Application” and fill in the application name and redirect URI.
    Google Application Type
  • Download the google Client ID and Client Secret key from popup. These keys we need in the config file below.
    google clientID clientSecret

Create Folder Structure

Let’s now create a folder structure of files upload to the google drive PHP script before proceeding further. It helps you to organize and manage script files.

Basically, we need the following file structure to get started.

  • config.php: to store the Google API keys and database details
  • dbConnect.php: to make a connection with the database
  • index.php: to load the HTML upload form
  • upload.php: to upload the file details to database
  • upload-file-to-drive.php: to upload the files to google drive an sync it
  • GoogleDriveApi.class.php: google drive api handler class
  • style.css: to style the upload form

So let’s create a main folder “files-upload-to-drive” and in this folder create all the above files one by one. We will see the code below.

Create Database and Table

We also need a database, so let’s create a new database “google_drive” (you can take any name), and then import the following SQL code to make a table inside.

Create a Configuration File

Let’s create a “config.php” file and add all the configuration-related data in this file. In this file, we will declare const variables for database details and google API configuration details.

config.php

So add the configuration details of the database and google API. The database details you can get from the server and google API client ID and secret key you can be found in the google console. You just have created the above by following the steps.

Download Google Drive API PHP Library

Let’s first, download the google drive API PHP library, you can copy the following code and save it as a “GoogleDriveApi.class.php“.

This library we will use to authenticate the account and access the google drive files and folder with the API requests.

In this library, we will make three main functions getAccessToken() to get authenticate, uploadFileToDrive() to upload the files in drive, and uploadFileMeta() to upload the file meta details in database.

GoogleDriveApi.class.php

Replace your defined constant in the config.php file within this drive API library. You can customize this library as per your requirements.

Create Database Connection

We will create a “dbConnect.php” file and make a database connection in this file using the database configuration details that are defined in the config.php file.

We will make a new instance of mysqli() and pass the database host, username, password, and database name. Then check whether the database connection is established or not using the connect_error property.

dbConnect.php

Create File Upload Form File

Now we will create a new “index.php” file. In this file, we will create an HTML form to select files and then upload them to google drive using the PHP library to make an API request.

index.php

You can style this landing page to upload the files to google drive as you want. You can also add google reCAPTCHA to verify before submitting the form. We just make the simple form using bootstrap.

Note: Make sure you have added the value of action attribute to a filename and the enctype attribute to multipart/form-data.

Store File Details in Database

To store the file details in the database, we will create a file “upload.php“. In this file, we will validate the required fields and store the file details in the database table “drive_files“.

upload.php

In the above code, first, we get the value of the input field using the $_FILES PHP global variable. Then we validated the required field and check the correct file type.

Then we used the SQL query function to insert the data into the database, but you can use a PDO statements to prevent the SQL injection.

After that, we first upload the file to our local server and insert the file details like name, mime, etc in the database. And finally redirected to OAuth URL for authentication.

Upload File to Google Drive

This is the main operation to make an API request to upload the files to google drive using the PHP library.

So, create a file “upload-file-to-drive.php“. When a user is successfully authenticated then the user will redirect to this file to handle the operation of uploading the files to google drive.

upload-file-to-drive.php

In the above code, first, we load the GoogleDriveAPi class file and the dbConnect file. Then get the OAuth code from the query string of the URL using the $_GET variable.

Then get the file info from the local database using the reference id from the session. Next, get the file from server using file_get_contents() function and also get mime type using mime_content_type() function.

Then use the getAccessToken(), uploadFileToDrive(), and updateFileMeta() function to get the token and upload the file and file info to drive.

Finally, show the successfully uploaded status and file access link of the google drive file. Visit that link and see your uploaded file.

Google Drive upload file form

Hope you like it, please share it with your friends and in social groups to help someone else. If you have any queries please let me know in comment or contact me.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment