I’m trying to get a list of all files in a particular Google Drive folder using PHP and cURL. I’ve successfully retrieved all files and folders from the root directory, but I’m struggling to narrow it down 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?trashed=false");
$result = curl_exec($curl);
print_r($result);
However, when I try to get files from a specific folder (let’s call it ‘my_videos’), I get a 404 error:
$folder = 'my_videos';
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?
hey elizabeths, i had similar issue. try using the folder ID instead of name:\n\ncurl_setopt($curl, CURLOPT_URL, “https://www.googleapis.com/drive/v3/files?q=‘FOLDER_ID’ in parents”);\n\nu can get folder ID from drive URL when ur in that folder. hope this helps!
I’ve dealt with this exact problem before, and I can tell you it’s a bit tricky. The key is using the folder ID, not the name. Here’s what worked for me:
First, get the folder ID from the Google Drive URL when you’re in that folder. It’s usually a long string of letters and numbers.
Then, modify your cURL request like this:
$folderId = 'your_folder_id_here';
curl_setopt($curl, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files?q='$folderId' in parents&trashed=false");
This should fetch all the files from your specific folder. Just remember to replace ‘your_folder_id_here’ with the actual ID you got from the URL.
Also, make sure your access token has the necessary permissions to access that folder. If it doesn’t, you’ll need to update your OAuth 2.0 scope to include https://www.googleapis.com/auth/drive.readonly or https://www.googleapis.com/auth/drive, depending on what you’re trying to do.
Using the folder ID is essential when narrowing down file queries on Google Drive. Instead of trying to fetch files by using the folder name, which leads to errors, you can obtain the folder ID from the URL when you open the folder in Google Drive. Replace the folder name in your query with this ID. For instance, assign your folder ID to a variable and update the cURL URL to include the query with the ID and the parameter trashed=false. This method ensures that only the files within the desired folder are retrieved.