Hey everyone! I’m trying to figure out how to upload files to a specific folder on Google Drive using their API and PHP. Right now, my code is uploading files to the root directory, but I need them to go into a different folder.
Here’s a simplified version of what I’m working with:
<?php
require_once 'google-api-php-client/autoload.php';
$client = new Google_Client();
$client->setClientId('my_client_id');
$client->setClientSecret('my_client_secret');
$client->setRedirectUri('http://my-redirect-uri.com');
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);
$drive = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile([
'name' => 'my_video.mp4',
'parents' => ['FOLDER_ID_HERE']
]);
$content = file_get_contents('local_video.mp4');
$file = $drive->files->create($fileMetadata, [
'data' => $content,
'mimeType' => 'video/mp4',
'uploadType' => 'multipart'
]);
print_r($file);
I’ve tried a few solutions from other posts, but they didn’t work for me. Any ideas on what I’m missing? Thanks!
hey, i had a similar problem. make sure ur using the right folder ID. u can find it in the URL when u open the folder in Drive. just replace ‘FOLDER_ID_HERE’ with that. also check if ur account has permission to write to that folder. good luck!
I’ve been working with the Google Drive API for a while now, and I can share some insights that might help. One thing to keep in mind is that the ‘parents’ array in your file metadata can actually accept multiple folder IDs. This is useful if you want to place the file in more than one folder simultaneously.
Here’s a pro tip: instead of hardcoding the folder ID, you might want to create a function that searches for the folder by name. This way, if the folder structure changes, your code won’t break. Something like:
function getFolderId($drive, $folderName) {
$results = $drive->files->listFiles([
'q' => "mimeType='application/vnd.google-apps.folder' and name='$folderName'",
'fields' => 'files(id)'
]);
return !empty($results->files) ? $results->files[0]->id : null;
}
Then you can use it like this:
$folderId = getFolderId($drive, ‘Your Folder Name’);
$fileMetadata[‘parents’] = [$folderId];
This approach has saved me countless hours of debugging and maintenance. Hope this helps!
I’ve dealt with this issue before, and the solution is actually quite straightforward. You’re on the right track with the ‘parents’ field in your $fileMetadata array. The key is to ensure you’re using a valid folder ID.
First, retrieve the ID of the target folder from its URL in Google Drive. Once you have the correct folder ID, replace ‘FOLDER_ID_HERE’ with that value. For example:
$fileMetadata = new Google_Service_Drive_DriveFile([
‘name’ => ‘my_video.mp4’,
‘parents’ => [‘1a2b3c4d5e6f7g8h9i0j’]
]);
If issues persist, verify your authentication and confirm the account has write permissions for the folder. Additionally, consider implementing try-catch blocks to capture and debug potential errors.