I’m working with the PHP Google Drive API to create directories. Right now my code makes folders accessible to everyone, but that’s not what I want.
I need to restrict access so only the account owner (whose credentials are in my JSON file) and maybe one or two specific email addresses can view the folder. I tried looking for solutions online but nothing worked properly.
Here’s my current code:
$googleDriveClient = setup_drive_service();
$directory_name = 'my_folder_2024';
// Create folder metadata
$directoryData = new Google_Service_Drive_DriveFile([
'name' => $directory_name,
'mimeType' => 'application/vnd.google-apps.folder',
]);
// Make the directory
$newDirectory = $googleDriveClient->files->create($directoryData, [
'fields' => 'id',
]);
if ($newDirectory) {
// This makes it public - I don't want this
$accessRule = new Google_Service_Drive_Permission([
'type' => 'anyone',
'role' => 'reader',
]);
$googleDriveClient->permissions->create($newDirectory->id, $accessRule);
}
I also tried this approach but it didn’t work:
if ($newDirectory) {
// Try to remove public access
$googleDriveClient->permissions->delete($newDirectory->id, 'anyone');
// Add specific users
$allowedUsers = ['[email protected]', '[email protected]'];
foreach ($allowedUsers as $userEmail) {
$userAccess = new Google_Service_Drive_Permission([
'type' => 'user',
'role' => 'editor',
'emailAddress' => $userEmail,
]);
$googleDriveClient->permissions->create($newDirectory->id, $userAccess);
}
}
How can I properly set up restricted permissions for my Google Drive folders?