DropPHP – simple PHP Dropbox API Client without cURL
DropPHP provides a simple interface for Dropbox’s REST API to list, download and upload files.
For authentication it uses OAuthSimple, HTTPS requests are made with PHP’s built in stream wrapper. It does not require any special PHP libarys like PECL, cURL or OAUTH.
It is released under a BSD license and there is a GitHub page ChangeDiva.
Functions
The class DropboxClient provides the following API functions.
On failure a DropboxException is thrown, so make sure you call the functions in a try-catch block.
Functions having argument dropbox_file/dropbox_path accept this to be a string or file/folder metadata Download FoxPlayer.
GetAccountInfo() | Retrieves information about the user’s account. Returns an object with account data. |
---|---|
GetMetadata($dropbox_path) | Retrieves file and folder metadata 쯔바이. |
GetFiles($dropbox_path=”, $recursive=false) | Get file list of a folder. Returns an array where keys the file paths and values metadata. If $recursive is true, all sub-folders are recursivly scanned. Note that this can take some time because each sub-folder causes a new API request. |
DownloadFile($dropbox_file, $dest_path=”, $revision=-1) | Downloads a file to the specified location on the webserver Download Internet Explorer 11 file. The destionation directory has to exist.
$revision: The revision of the file to download. This defaults to the most recent revision. Returns metadata of the downloaded file. |
UploadFile($src_file, $dropbox_path=”) | Uploads a file from webserver to dropbox. Returns metadata of the uploaded file lg intelligent update 다운로드. |
GetLink($dropbox_file, $preview=true) | Returns a download link to a file. If $preview is true it creates a link users can use to view a preview of the file in a web browser. |
Delta($cursor) | Retrieves file changes. See delta |
Copy($from_path, $to_path) | Copies a file or folder to a new location Download the New People Bible. |
CreateFolder($path) | Creates a folder. |
Delete($path) | Deletes a file or folder. |
Move($from_path, $to_path) | Moves a file or folder to a new location. |
Dropbox REST API Authentication
Dropbox Rest API uses OAuth for authentication 산타나. When the Dropbox is accessed for the first time, the PHP Client retrieves a request token from Dropbox webservice. This token needs to be authorized for a Dropbox user account, so the user is redirected to an authentication page where they allow the app access to their account. Afterwards the user is redirected back to the web application, where DropPHP uses the previously stored request token (and secret) to retrieve an access token certificate form. This access token is saved and will be used to authorize any further API requests.
Setup
- Create a Dropbox App
- Copy & Paste the App key and secret to the PHP code, that creates the DropboxClient object:
$dropbox = new DropboxClient(array('app_key' => "YOUR_APP_KEY",
‘app_secret’ => “YOUR_APP_SECRET”,’app_full_access’ => false, // if the app has full or folder only access),’en’); // language/country code - See sample.php. Your web application should run like the following logic (pseudo code):
Load Access Token$dropbox->SetAccessTokenElseIf ThenLoad previously stored request token$dropbox->GetAccessToken (using the request token)Save Access TokenIf Then
Delete request token
Else
$dropbox->GetRequestToken
Save the request token secret
$dropbox->BuildAuthorizeUrl
Redirect to authorize url
Exit
EndIf
Do Dropbox stuff
Tokens
A token is an alpha-numeric code used to authorize API requests Naver Calendar pc. Each token has a secret key, which is like a password to use the token. DropPHP uses an array to store tokens:
Array
(
[t] => 6lj3i20m4fsgi6y
[s] => 2pn7x2bjsm3xvq8
)
At Index t is the actual token, s is the token secret. In sample.php, this array is just serialized and written to a file (function store_token) in the folder /tokens. You should use your own method to save and load tokens (i.e windows xp iso 한글 다운로드. MySQL). Of course you can put the tokens in PHP’s $_SESSION array, then you have have to re-authenticate every new session.
If you get a wrapper not found error, make sure the PHP extension OpenSLL is loaded in php.ini:
extension=php_openssl.dll
Did anybody else notice that size (regardless of the doc: https://www.dropbox.com/developers/core/docs#thumbnails) always returns “s” (max 64px).
Code here:
public function GetThumbnail($dropbox_file, $size = ‘m’, $format = ‘png’, $echo = false)
{ if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
$url = $this->cleanUrl(self::API_CONTENT_URL.”thumbnails/$this->rootPath/$dropbox_file”);
$content = http_build_query(array(‘format’ => $format, ‘size’ => $size),”,’&’);
$context = $this->createRequestContext($url, “GET”, $content);
if($this->useCurl) {
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
}
$thumb = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, NULL, $context);
if($echo) {
header(‘Content-type: image/’.$format);
echo $thumb;
unset($thumb);
return;
}
return $thumb;
}
v1.6 fixed the thumbnail size issue, also.
thank you fabi. you’re world-class. (:
Hi, i used the library all good like 3 weeks ago and now everytime i want to download a file say:
Fatal error: Uncaught exception ‘DropboxException’ with message ‘Download size mismatch!’
Hi nabil & Terrence,
update to latest version 1.6, this fixes the issue.
Don’t know if DropBox changed it, but the upload did not work for me. Then I noticed in the core API docs that for /files_put the path parameter cannot be a folder, it must contain the filename.
So when I changed the following line in the DropBoxClient
$url = $this->cleanUrl(self::API_CONTENT_URL.”/files_put/$this->rootPath/$dropbox_path”).”?$query”;
to
$url = $this->cleanUrl(self::API_CONTENT_URL.”/files_put/$this->rootPath/$dropbox_path”).”/”.basename($src_file).”?$query”;
it started working again. Took me a while to notice because I use this to back up my websites onto a DropBox account (dump database, zip all files, upload zip to DropBox), and the last CRON job that executes the backup-procedure returned an error.
BTW, you say this works without cURL, but there’s still a lot of pointers to cUrl (which I removed: using libraries adds a level of abstraction that makes debugging these kinds of errors very difficult – I never use libraries if I can avoid it).
Hi Stefam,
this is not a bug, $dropbox_path passed to the UploadFile function must be the full file path, NOT a path to the directory!
The client work without cURL, on initializiation it checks for cURL beeing installed and falls back to PHP wrappers if it could not find it.
You should always use libraries for performance reasons, cURL is faster than PHP HTTPS wrappers. The trick is to fall back to built in PHP functions if dependencies are not available.
Regards
Fabian
Hi Fabi,
I have downloaded version 1.6 above but the error is still there:
“Fatal error: Uncaught exception ‘DropboxException’ with message ‘Download size mismatch! (header: vs actual:54’ in”
The script downloads the temp file then upload to S3.
I also noticed that getting the files from an app folder includes the Getting Started.pdf file together with the files in the App folder. Using GetMetadata(). Not using delta because I’m not synching the files just getting the metadata to be listed on the database.
Kind regards,
Anthony
Hi Anthony,
please try this version: https://fabi.me/download/DropboxClient.zip
It gives more debug data if download fails.
Thanks Fabi. I will try this out.
Hi Fabi,
This is what I got from the updated DropboxClient file that you gave.
Thanks and regards,
Anthony
Fatal error: Uncaught exception ‘DropboxException’ with message ‘Could not retrieve meta data from header data: Array ( [0] => HTTP/1.1 403 Forbidden [1] => Server: nginx [2] => Date: Sun, 06 Oct 2013 10:14:28 GMT [3] => Content-Type: application/json [4] => Transfer-Encoding: chunked [5] => Connection: keep-alive [6] =>
Can you post the DownloadFile call including the parameters you are passing?
Hi Fabi,
Here is my call:
$GLOBALS[‘dropbox’]->DownloadFile(‘/testfolder/bt-m2-timing.mp4′, dirname(__FILE__).’/media/’.$values[1].’/’.$filename);
I only have 2 parameters. The dropbox file and the destinatio path.
Thanks
Hi Fabi,
I had a wrong App access details from before but after I have updated it to the right ones. I git this error on download function with the same parameters as above.
Fatal error: Uncaught exception ‘DropboxException’ with message ‘Could not retrieve meta data from header data: Array ( [0] => HTTP/1.1 400 Bad Request [1] => Server: nginx [2] => Date: Wed, 09 Oct 2013 09:17:33 GMT [3] => Content-Type: application/json [4] => Transfer-Encoding: chunked [5] => Connection: keep-alive [6] => ) ‘
Thanks,
Anthony
Hi Fabi,
Digging more into the DropboxClient. The $response_headers variable gets:
array(7) {
[0]=>
string(24) “HTTP/1.1 400 Bad Request”
[1]=>
string(13) “Server: nginx”
[2]=>
string(35) “Date: Wed, 09 Oct 2013 10:57:45 GMT”
[3]=>
string(30) “Content-Type: application/json”
[4]=>
string(26) “Transfer-Encoding: chunked”
[5]=>
string(22) “Connection: keep-alive”
[6]=>
string(0) “”
}
$context has “Resource id #10”
$url is “https://api-content.dropbox.com/1/files/dropbox/testfolder/media-flow.jpg”
Here is my download file call:
DownloadFile($dropbox_file=’/testfolder/mediamasher-flow.jpg’, $dest_path=’/home/mediamas/public_html/testcalls/mediamasher_uploader_engine/media/2/mediamasher-flow.jpg’)
Hi Fabi,
I have another findings. The file actually downloaded but it can’t be opened. Tried an MP4 and a JPG file. Both have errors when opening on my machine.
regards,
Anthony
Anthony, have you tried SetUseCUrl(true/false) ?
Hi Fabi,
Thank you for your support and creating DropPHP.
I got the problem solved just now.
The previous developer was calling the DropboxClient like this:
$dropbox = new DropboxClient(array(
‘app_key’ => DROPBOX_CONSUMER_KEY,
‘app_secret’ => DROPBOX_CONSUMER_SECRET,
‘app_full_access’ => true
),’en’);
That is why he’s getting Getting Started.pdf also from the Dropbox root.
I changed ‘app_full_access’=>true to false but the issues above arose.
I saw this code in DropboxClient:
$this->rootPath = empty($app_params[‘app_full_access’]) ? “sandbox” : “dropbox”;
and I changed it to:
$this->rootPath = ($app_params[‘app_full_access’] ? “dropbox” : “sandbox”);
It solved the 400 Error for me.
I think empty($app_params[‘app_full_access’]) defaults to dropbox and not to sandbox if the parameter is false, true, or if you pass any string or integer to it.
Best regards,
Anthony
Hi Fabi,
I am finding following exception. Please guide me to run sample.php properly…
Warning: file_put_contents(tokens/wgRUT5FVLUn8GHX0.token) [function.file-put-contents]: failed to open stream: No such file or directory in D:\PHP\application\dropbox\DropPHP-master\sample.php on line 106
Could not store token! Make sure that the directory `tokens` exists and is writable!
Hi I came across your client class file for dropbox php api. I am trying to use but I am unable to get meta information for all files of logged in user. Following is the output I receive:
Files:
Array
(
[0] => abc.html
[1] => B1.docx
[2] => Getting Started.pdf
[3] => test_download_abc.html
[4] => test_download_Getting Started.pdf
[5] => xyz.html
)
Meta data of /abc.html:
stdClass Object
(
[revision] => 4
[rev] => 4131fc57f
[thumb_exists] =>
[bytes] => 361
[modified] => Thu, 26 Sep 2013 04:55:26 +0000
[client_mtime] => Thu, 26 Sep 2013 04:55:26 +0000
[path] => /abc.html
[is_dir] =>
[icon] => page_white_code
[root] => dropbox
[mime_type] => text/html
[size] => 361 bytes
)
this is the response obtained kindly tell me why other files in array are not considered for meta information
can u send me the code
can u send me the code
Awesome things here. I am very happy to peer your
post. Thanks so much and I am taking a look forward to touch you.
Will you kindly drop me a mail?
Moin,
ich hab’ da mal ´ne kurze Frage:
Ist es möglich, Dateien aus einem Ordner in meiner Dropbox automatisch auf den Server zu laden?
Wäre echt praktisch für mark2 (Flat-File Based Blogging-System an dem ich arbeite)..
Gruß
Flo
Hi, I’ve installed and configured your script but when I try to upload a picture I keep getting this error:
stdClass Object
(
[error] => Access token does not belong to this app.
)
done!
Any ideas?
Thanks!
Already found what was causing this error.
If you, like me, are testing with various dropbox accounts and getting this odd error, delete the access.token under the token folder.
The script was using an access.token from another instance.
Hope it helps.
J
Hi Fabi,
Firstly what an excellent script, great work!
I am having issues with the length of time it takes to upload, i am trying to upload a file in the size of circa 400MB and its taking about 10 hours to complete, can you let me know if there is any settings i could tweak in order to get this going quicker?
The server is using curl and when checked is returning 1 for function_exists(‘curl_init’) so i assume its running via curl.
The server is hosted on a big pipe so bandwidth speed should not be an issue?
Thanks in advance for any ideas.
Glenn
Hi Glenn,
try increasing the UPLOAD_CHUNK_SIZE:
https://github.com/f4bsch/DropPHP/blob/master/DropboxClient.php#L26
Regards
Fabian
Thanks Fabi, that had taken the time down to 1 hour.
hello fabi
how to retrive files and folder details using dropbox api in php
hi fabi, i am trying to create a “drop-zone” to my dropbox account within a .php application. can you send me an email so i can explain further?
Warning: file_put_contents(tokens/X0ae9FGYhdikFe39.token) [function.file-put-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\DropPHP\sample.php on line 106
Could not store token! Make sure that the directory `tokens` exists and is writable!
I want to do a web app, where users will put the credentials and I upload the data to their dropbox account. I see that I need to create an app with my account and I get a key, But where in the library I put the credentials of the user so upload files to different accounts?
Thank you
[…] have found a script I am trying to work with to make this possible. It is one made by Fabi to download and upload files […]
[…] have found a script I am trying to work with to make this possible. It is one made by Fabi to download and upload files […]
Hi Fabi,
good Job, thank you.
Can you tell me, how i can get the process of a file during the download?
Thanks Michael
i want to ask few questions bro
1) how we can increase image thumbanil size ?
2) how we can limit the search record query ?
3) why you upload 1st image again with concatinate string “test_download_” and download it, and can how we can change the download image path ?
if i call app_key and app_secret for every user within a loop than how can i manage tokens for each user in tokens folder ?
Hi,
first of all thanks for the great script. i have a question!
i want to download ALL files from my app_folder into a specific folder on my local / online-folder. can you please help me out?
many thanks
I was using ur API and build a web app. But when i try to delete one image from my dropbox, the api is throwing error:
Fatal error: Uncaught exception ‘DropboxException’ with message ‘Path ‘/fcb2.jpg”‘ not found’ in C:\xampp\htdocs\project4\DropboxClient.php:597 Stack trace: #0 C:\xampp\htdocs\project4\DropboxClient.php(617): DropboxClient::checkForError(Object(stdClass)) #1 C:\xampp\htdocs\project4\DropboxClient.php(450): DropboxClient->apiCall(‘fileops/delete’, ‘POST’, Array) #2 C:\xampp\htdocs\project4\album.php(93): DropboxClient->Delete(‘/FCB2.jpg”‘) #3 {main} thrown in C:\xampp\htdocs\project4\DropboxClient.php on line 597
I am calling the function as :
if(isset($_POST[“delete”])){
$path = substr($_GET[“id”], 1);
$meta = $dropbox->Delete($path);
//print_r($meta);
}
where im passing the path as ‘id’ in the query string of the url.
Kindly provide any sort of assistance.
I get a key, But where in the library I put the credentials of the user so upload files to different accounts? Thank you
Dropbox V1 API endooints stop working on September 20 – any plans to update DropPHP to support the new API?
There are few issues with DropboxClient.php
1. in function copy()
Instead of return $this->apiCall( “fileops/copy”, array(
it should be
return $this->apiCall( “2/files/copy_v2”, array(
2. In the same function ‘root’ should not be one of parameter.
I am only using copy function and come across these issues.
Hope this may help some one.
Appreciate your effort.
Hey Anto, is this the only issue with this api client as far as you know?
Hey Anto, is this the only issue with this api client as far as you know?