Home > Software design >  How to delete a file in a google drive shared drive folder using php?
How to delete a file in a google drive shared drive folder using php?

Time:11-29

All I need is to delete a file which is inside my shared drive folder using google/apiclient using php , this is my code below .

session_start();

require __DIR__ . '/vendor/autoload.php'; // ready the API to upload to drive

use Google\Client;
use Google\Service\Drive;

if (isset($_POST['file'])) {
    $file = $_POST['file'];

        $client = new Client();
        putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);

        $delete = $driveService->files->delete($file);

        if ($delete) {
            $_SESSION['success'] = "Video deleted successfully";
            header("Location: upload");
        }

}



CodePudding user response:

If your client has permission for deleting the file from the shared Drive, how about the following modification?

From:

$delete = $driveService->files->delete($file);

To:

$fileId = "###"; // Please set the file ID of the file you want to delete.
try {
    $driveService->files->delete($fileId, array('supportsAllDrives' => true));
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
  • In this case, when the file is deleted, no value is returned. Please be careful about this.

Note:

  • When I tested this script, I confirmed that a file in a shared Drive could be deleted. But, if an error occurs, please confirm the permission of your client, again.

Reference:

  • Related