Dropbox API – PHP function for file download

A complete documentation can be found on Dropbox API page. Dropbox already stop supporting PHP SDK for the API, thus I googled for guidance but unfortunately not so many references for the working code and finally I got it working with try and error method.

My intention is as below:-

1. Get a webhook notification upon any new file creation in my account.
2. Read the root folder
3. Process any text files if any
4. Move text files to subfolder

Here is the sample of working PHP code using curl:


function getFile($path)
{
global $access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://content.dropboxapi.com/2/files/download');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Authorization: Bearer '.$access_token;
$headers[] = 'Content-Type: text/plain; charset=utf-8';
$headers[] = 'Dropbox-API-Arg: {"path":"' . $path . '"}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error '.curl_error($ch);
}
curl_close ($ch);
return($result);
}

Notice this line:

$headers[] = 'Dropbox-API-Arg: {"path":"' . $path . '"}';

It is there to replace my initial line like this:

curl_setopt($ch, CURLOPT_POSTFIELDS, '{"cursor": "'.$path.'"}');

because CURL keep colaining this error:

Error in call to API function "files/download": The request body is supposed to be empty, but it isn't;

Hope this entry will help to those looking for a download file script via Dropbox API.

Prev PostKerja kuat adalah jihad
Next PostWorking fail2ban with asterisk and freepbx

Leave a reply