I’m trying to get a list of all files in a particular Google Drive folder using PHP and cURL. I’ve managed to fetch all files and folders from the main drive, but I’m stuck when it comes to a specific folder.
Here’s what I’ve done so far:
$token = 'my_access_token';
$headers = [
"Authorization: Bearer $token",
"Content-Type: application/json"
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
// This works for all files
curl_setopt($curl, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files");
$result = curl_exec($curl);
print_r($result);
But when I try to get files from a specific folder (let’s call it ‘my_special_folder’), I get a 404 error:
$folder = 'my_special_folder';
curl_setopt($curl, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files?q='$folder' in parents");
Any ideas on what I’m doing wrong? How can I correctly fetch files from a specific folder?
I’ve encountered this issue before, and the key is using the folder’s ID rather than its name. Here’s a more efficient approach:
Fetch the folder ID first:
$folderName = ‘my_special_folder’;
$query = urlencode(“name=‘$folderName’ and mimeType=‘application/vnd.google-apps.folder’”);
curl_setopt($curl, CURLOPT_URL, “https://www.googleapis.com/drive/v3/files?q=$query”);
$result = json_decode(curl_exec($curl), true);
$folderId = $result[‘files’][0][‘id’] ?? null;
Then retrieve files using the folder ID:
if ($folderId) {
$query = urlencode(“‘$folderId’ in parents”);
curl_setopt($curl, CURLOPT_URL, “https://www.googleapis.com/drive/v3/files?q=$query”);
$files = curl_exec($curl);
// Process $files as needed
}
This method is more direct and avoids potential issues with special characters in folder names.