Search code examples
phpgoogle-drive-api

how to properly get lst of all files in a folder in google drive using Curl php


Am following this google drive Search API Google Drive API I used the code below to successfully display all files and folder in google drive and is working fine.

$access_token = 'xxxxxxxx';
$headers = array(
"Authorization: Bearer $access_token",
"Content-Type: application/json"
);



$ch = curl_init();                                                       
//curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files?trashed=false");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($ch);

var_dump($response);

Here is my issue

I need to get all files in a specific folder eg myvideo_folder

I have tried Code below but cannot get it to work. it throw error

{ "error": { "code": 404, "message": "File not found: .", "errors": [ { "message": "File not found: .", "domain": "global", "reason": "notFound", "location": "fileId", "locationType": "parameter" } ] } } " 

Here is the code

$access_token = 'xxxxx';
$headers = array(
"Authorization: Bearer $access_token",
"Content-Type: application/json"
);

$folder_name='myvideo_folder';
$ch = curl_init();                                                       
//curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files?q='$folder_name' in parents");
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files?q=%27$folder_name%27%20in%20parents");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($ch);

var_dump($response);

Solution

  • First need to get the google drive folder id. For that, query with

    $query1 = "name='".$foldername."' and mimeType='application/vnd.google-apps.folder' and trashed=false";
    

    Then again requery with

    $query2 = "$folderid in parents";
    

    This way you can get the files.

    Although, it is better and simple to use

    Google drive api client for PHP : github.com/googleapis/google-api-php-client