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.
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
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.
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.
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 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.
<?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($ch, CURLOPT_URL, self::OAUTH2_TOKEN_URI);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_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($ch, CURLOPT_URL, $apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_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;
}
}
}
?>
In the config.php
file, Google API configuration constant variables are defined.
Google API constants:
https://www.googleapis.com/auth/drive
).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.
Create an HTML form to allow the user to input the ID of the Google Drive file that wanted to delete.
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>
The google_drive_sync.php
file handles the file removal process with Google Drive API using PHP.
When the user redirects back after the authentication with their Google account.
GetAccessToken()
function of the GoogleDriveApi class.DeleteFile()
function of the GoogleDriveApi class.<?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_ID, REDIRECT_URI, GOOGLE_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.
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 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.
Add Event to Google Calendar using PHP
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