Delete Files from Google Drive using PHP

Drive API allows to interact with Google Drive storage and manage files/folders programmatically. We can access or manage files in Google Drive from website using this REST API. The Google Drive API supports many popular programming languages and PHP is one of them. In PHP, the cURL service can be used to make HTTP requests to Drive REST API. We have already shared the tutorials to upload files to Google Drive and download files from Google Drive using PHP. In this tutorial, we will explain how to delete files from Google Drive via REST API using PHP.

In this example script, we will implement the following functionality to delete files from Google Drive with PHP.

  • Build an HTML form to input the ID of the Google Drive file.
  • Authenticate with Drive using Google account.
  • Use Drive API v3 to delete files from Google Drive with PHP.
  • Get the file delete status from Drive API.

Before getting started to build a PHP script to delete files from Google drive using PHP, take a look at the file structure.

google_drive_file_delete_with_php/
├── config.php
├── index.php
├── google_drive_sync.php
├── GoogleDriveApi.class.php
└── css/
    └── style.css

Create Google Project and Enable Drive API

The Client ID and Client Secret are required to make API calls to Google Drive. If you already have an existing project at the Google API console, create OAuth Client IDs from there. But you have to make sure that Google Drive API is enabled in this existing Google API console application.

If you don’t have any application at the Google API console, follow the below steps to register your application and create OAuth Client IDs on Google Developers Console.

  • Go to the Google API Console.
  • Select an existing project from the projects list, or click NEW PROJECT to create a new project:
    google-api-console-project-create-codexworld
    • Type the Project Name.
    • The project ID will be created automatically under the Project Name field. (Optional) You can change this project ID by the Edit link, but it should be unique worldwide.
    • Click the CREATE button.
  • Select the newly created project and enable the Google Drive API service.
    • In the sidebar, select Library under the APIs & Services section.
    • Search for the Google Drive API service in the API list and select Google Drive API.
    • Click the ENABLE button to make the Google Drive API Library available.
  • In the sidebar, select Credentials under the APIs & Services section.
  • Select the OAuth consent screen tab, specify the consent screen settings.
    • Enter the Application name.
    • Choose a Support email.
    • Specify the Authorized domains which will be allowed to authenticate using OAuth.
    • Click the Save button.
  • Select the Credentials tab, click the Create credentials drop-down and select OAuth client ID.
    • In the Application type section, select Web application.
    • In the Authorized redirect URIs field, specify the redirect URL.
    • Click the Create button.

A dialog box will appear with OAuth client details, note the Client ID and Client secret for later use in the script. This Client ID and Client secret allow you to access the Google Drive API.

google-api-console-project-oauth-api-key-client-id-secret-codexworld

Note that: The Client ID and Client secret need to be specified at the time of the Google Drive API call. Also, the Authorized redirect URIs must be matched with the Redirect URL specified in the script.

Google Drive API Handler PHP Library

Google provides a PHP client library to make Drive API calls, but it contains many additional services that come with a huge number of files and are large in size. To make the process simple, we will build a custom library to handle the Google Drive API calls using PHP.

This Google Drive API class helps to authenticate with a Google account and access the Drive API using PHP cURL. This custom PHP library will use Google Drive API v3 to handle authentication and file delete processes.

  • GetAccessToken() – Fetch the access token from Google OAuth 2 API using the authentication code.
  • DeleteFile() – Execute Files:delete request to Drive API using PHP cURL.
    • The request type must be DELETE.
    • The fileId must be specified in the parameter of the API URL.
<?php 
/**
 *
 * This Google Drive API handler class is a custom PHP library to handle the Google Drive API calls.
 *
 * @class        GoogleDriveApi
 * @author        CodexWorld
 * @link        http://www.codexworld.com
 * @version        1.0
 */
class GoogleDriveApi {
    const 
OAUTH2_TOKEN_URI 'https://oauth2.googleapis.com/token';
    const 
DRIVE_FILE_UPLOAD_URI 'https://www.googleapis.com/upload/drive/v3/files';
    const 
DRIVE_FILES_URI 'https://www.googleapis.com/drive/v3/files/';
    
    
function __construct($params = array()) {
        if (
count($params) > 0){
            
$this->initialize($params);        
        }
    }
    
    function 
initialize($params = array()) {
        if (
count($params) > 0){
            foreach (
$params as $key => $val){
                if (isset(
$this->$key)){
                    
$this->$key $val;
                }
            }        
        }
    }
    
    public function 
GetAccessToken($client_id$redirect_uri$client_secret$code) {
        
$curlPost 'client_id=' $client_id '&redirect_uri=' $redirect_uri '&client_secret=' $client_secret '&code='$code '&grant_type=authorization_code';
        
$ch curl_init();        
        
curl_setopt($chCURLOPT_URLself::OAUTH2_TOKEN_URI);        
        
curl_setopt($chCURLOPT_RETURNTRANSFER1);        
        
curl_setopt($chCURLOPT_POST1);        
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
        
curl_setopt($chCURLOPT_POSTFIELDS$curlPost);    
        
$data json_decode(curl_exec($ch), true);
        
$http_code curl_getinfo($ch,CURLINFO_HTTP_CODE);
        
        if (
$http_code != 200) {
            
$error_msg 'Failed to receieve access token';
            if (
curl_errno($ch)) {
                
$error_msg curl_error($ch);
            }else{
                
$error_msg = !empty($data['error']['message'])?$data['error']['message']:'';
            }
            throw new 
Exception('Error '.$http_code.': '.$error_msg);
        }
            
        return 
$data;
    }
    
    public function 
DeleteFile($access_token$file_id$googleOauthURL '') {
        
$apiURL self::DRIVE_FILES_URI $file_id;
        
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL$apiURL);
        
curl_setopt($chCURLOPT_RETURNTRANSFER1);
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE); 
        
curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json''Authorization: Bearer '$access_token)); 
        
curl_setopt($chCURLOPT_CUSTOMREQUEST'DELETE');
        
        
$data json_decode(curl_exec($ch), true);
        
        
$http_code curl_getinfo($ch,CURLINFO_HTTP_CODE);         
         
        if(
$http_code != 200 && $http_code != 204){
            
$error_msg 'Failed to delete file.'
            if (
curl_errno($ch)) { 
                
$error_msg curl_error($ch); 
            }else{
                
$error_msg = !empty($data['error']['message'])?$data['error']['message']:'';
            }
            
            if(
$http_code == 401 && !empty($googleOauthURL)){
                unset(
$_SESSION['google_access_token']);
                
$error_msg .= '<br/>Click to <a href="'.$googleOauthURL.'">authenticate with Google Drive</a>';
            }
            
            throw new 
Exception('Error '.$http_code.': '.$error_msg);
        }else{
            return 
true;
        }
    }
}
?>

Google API Configuration (config.php)

In the config.php file, Google API configuration constant variables are defined.

Google API constants:

  • GOOGLE_CLIENT_ID – Specify the Google Project Client ID.
  • GOOGLE_CLIENT_SECRET – Specify the Google Project Client Secret.
  • GOOGLE_OAUTH_SCOPE – Specify the OAuth scope for Google authentication (set to https://www.googleapis.com/auth/drive).
  • REDIRECT_URI – Specify the Callback URL.

Google OAuth URL:
This URL format is predefined and doesn’t require any changes.

  • $googleOauthURL – The URL that allows the user to authenticate with Google account.
<?php 

// Google API configuration
define('GOOGLE_CLIENT_ID''Google_Project_Client_ID'); 
define('GOOGLE_CLIENT_SECRET''Google_Project_Client_Secret'); 
define('GOOGLE_OAUTH_SCOPE''https://www.googleapis.com/auth/drive');
define('REDIRECT_URI''https://www.example.com/google_drive_sync.php');

// Start session
if(!session_id()) session_start();

// Google OAuth URL
$googleOauthURL 'https://accounts.google.com/o/oauth2/auth?scope=' urlencode(GOOGLE_OAUTH_SCOPE) . '&redirect_uri=' REDIRECT_URI '&response_type=code&client_id=' GOOGLE_CLIENT_ID '&access_type=online';

?>

Note that: The Client ID and Client Secret can be found on the Google API Manager page of the API Console project.

File ID Input HTML Form (index.php)

Create an HTML form to allow the user to input the ID of the Google Drive file that wanted to delete.

  • On submission, the file ID is posted to the server-side script (google_drive_sync.php) for further processing.
<?php 
// Include configuration file
include_once 'config.php';

$status $statusMsg '';
if(!empty(
$_SESSION['status_response'])){
    
$status_response $_SESSION['status_response'];
    
$status $status_response['status'];
    
$statusMsg $status_response['status_msg'];
    
    unset(
$_SESSION['status_response']);
}
?> <!-- Status message --> <?php if(!empty($statusMsg)){ ?> <div class="alert alert-<?php echo $status?>"><?php echo $statusMsg?></div> <?php ?> <div class="col-md-12"> <form method="post" action="google_drive_sync.php" class="form"> <div class="form-group"> <label>Drive File ID:</label> <input type="text" name="file_id" class="form-control" placeholder="Enter ID of Google Drive file"> </div> <div class="form-group"> <input type="submit" class="form-control btn-primary" name="submit" value="Delete from Drive"/> </div> </form> </div>

Delete File from Google Drive (google_drive_sync.php)

The google_drive_sync.php file handles the file removal process with Google Drive API using PHP.

  • Include and initialize the Google Drive API handler PHP library.
  • Get file ID from the input field using the PHP $_POST method.
  • Validate input to check whether mandatory fields are empty.
  • Store the given Google Drive file ID in SESSION with PHP.
  • Redirect user to the OAuth URL for authentication with Google account.

When the user redirects back after the authentication with their Google account.

  • Retrieve OAuth code from the query string of the URL using the PHP $_GET variable.
  • Get the file ID of the Google Drive from SESSION.
  • Get access token by authentication code using GetAccessToken() function of the GoogleDriveApi class.
  • Remove/delete the file from Google drive based on file ID using the DeleteFile() function of the GoogleDriveApi class.
  • Display the status of the Google Drive file delete request.
<?php     
// Include configuration file
require_once 'config.php';

// Include and initialize Google Drive API handler class
include_once 'GoogleDriveApi.class.php';
$GoogleDriveApi = new GoogleDriveApi();

$statusMsg $valErr $access_token '';
$status 'danger';

// If the form is submitted
if(isset($_POST['submit'])){
    
// Validate form input fields
    
if(empty($_POST["file_id"])){
        
$valErr .= 'Please enter ID of Google Drive file.';
    }
    
    
// Check whether user inputs are empty
    
if(empty($valErr)){
        
$drive_file_id $_POST["file_id"];
        
        
// Store reference ID of file in SESSION
        
$_SESSION['last_file_id'] = $drive_file_id;
        
        
// Get the access token
        
if(!empty($_SESSION['google_access_token'])){
            
$access_token $_SESSION['google_access_token'];
        }else{
            
// Redirect to the Google authentication site
            
header("Location: $googleOauthURL");
            exit();
        }
    }else{
        
$statusMsg '<p>Please fill all the mandatory fields:</p>'.trim($valErr'<br/>');
    }
}elseif(isset(
$_GET['code'])){
    
// Get file reference ID from SESSION
    
$drive_file_id $_SESSION['last_file_id'];

    if(!empty(
$drive_file_id)){
        
// Get the access token
        
if(!empty($_SESSION['google_access_token'])){
            
$access_token $_SESSION['google_access_token'];
        }else{
            
$data $GoogleDriveApi->GetAccessToken(GOOGLE_CLIENT_IDREDIRECT_URIGOOGLE_CLIENT_SECRET$_GET['code']);
            
$access_token $data['access_token'];
            
$_SESSION['google_access_token'] = $access_token;
        }
    }else{
        
$statusMsg 'File reference not found!';
    }
}else{
    
$statusMsg 'Unauthorized access!';
}

if(!empty(
$access_token)){
    
// Delete file from Google drive
    
try {
        
$drive_file_delete $GoogleDriveApi->DeleteFile($access_token$drive_file_id$googleOauthURL);
    } catch(
Exception $e) {
        
$api_error $e->getMessage();
    }
    
    if(
$drive_file_delete && empty($api_error)){
        
$status 'success'
        
$statusMsg "The file ID:$drive_file_id has been removed from Google Drive successfully!";
            
        unset(
$_SESSION['last_file_id']);
    }else{
        
$statusMsg 'File delete failed: '.$api_error;
    }
}else{
    unset(
$_SESSION['google_access_token']);
    
$statusMsg = !empty($statusMsg)?$statusMsg:'Failed to fetch access token! Click to <a href="'.$googleOauthURL.'">authenticate with Google Drive</a>';
}

$_SESSION['status_response'] = array('status' => $status'status_msg' => $statusMsg);

header("Location: index.php");
exit();

?>

Note that: This file URL must be set as Redirect URL in Authorized redirect URIs section of the Google API console project.

Important Notes:

If you want to delete the file from Google Drive other than the authenticated Google account, make sure the file sharing option is set to Anyone with the link with Editor permission.

google-drive-file-share-link-permission-editor-codexworld

Checklist for Testing:

Google Application Verification:
Google requires application verification to use Drive API. You need to submit the application for verification to make Google project public.

In the development mode, you can test it by adding Test Users in the OAuth consent screen of the Google application.

  • On the OAuth Client credentials page, click the OAuth consent screen link.
    google-api-console-oauth-client-credentials-codexworld
  • In the OAuth consent screen page, add users under the Test users section.
    google-api-console-oauth-consent-test-user-codexworld

Add Event to Google Calendar using PHP

Conclusion

Delete files from Google drive with REST API is an easy way to manage files from the website. You can delete files from Google Drive dynamically using PHP. Since the access token is stored in SESSION, the file delete request can execute without Google account authentication and files can be removed from the Google Drive account.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up