fabi.me

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.

DropPHP
DropPHP
master.zip.html
Version: 1.4
12 KiB
12876 Downloads
Details

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.

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. 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.
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.
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. This access token is saved and will be used to authorize any further API requests.

Setup

  1. Create a Dropbox App
  2. 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
  3. See sample.php. Your web application should run like the following logic (pseudo code):
    If ThenLoad Access Token$dropbox->SetAccessTokenElseIf ThenLoad previously stored request token$dropbox->GetAccessToken (using the request token)Save Access Token
    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. 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. 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

DropPHP
DropPHP
master.zip.html
Version: 1.4
12 KiB
12876 Downloads
Details
Rating: 3.9. From 22 votes.
Please wait...

Comments

  • Arpit Goyal says:

    hi,
    we are students from IIT-Delhi, we used your source to authorise a user’s dropbox, it worked fine.
    But when we are adding new function for creating folder on user’s account then it’s giving an error,
    [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
    in /home/edciitd/public_html/handa/DropboxClient.php on line 293

    So can you notify us by mail as soon as possible, as we are competing in a hack competion of 24hrs, so we kind of need its solution fast.

  • Fabi says:

    Hi,
    to create a new folder, this should work (not tested):
    $this->apiCall(“fileops/create_folder”, “POST”, array(‘root’ => , ‘path’ => ));

    If you still get an error, you should debug print the $url passed to file_get_contents in the apiCall function.

    Regards
    Fabian

  • Mell says:

    Hi,
    How can i delete file from dropbox (using one folder access) with PHP Client?

    regards

  • Partha says:

    Sir,

    I want to download file directly in user pc, i was trying GetLink function it is not working.

    please help me

  • Mary says:

    Hi,

    I tried running the sample.php file and it redirects me to dropbox and authenticates but then I get a request token not found error. I don’t know why this is because I assumed the $request_token = load_token($_GET[‘oauth_token’]); line would retrieve the token using GET.I don’t know if I have to add in something extra for the token to be found?

  • Fabi says:

    Hello Mary,
    the functions store_token and load_token are only for demonstration. If you want to use them you have to make sure the folder “tokens” exists and chmod it to 777.

  • sabana says:

    Hello,

    I used ur code and it worked fine. I want to create folder on dropbox in my app folder i coded the following

    function CreateFolder($dropbox_path)
    {
    return $this->apiCall(“fileops/create_folder/$this->rootPath/$dropbox_path”, “POST”);
    }

    function apiCall($path, $method, $params=array())
    {
    $url = $this->cleanUrl(self::API_URL.$path);
    $content = http_build_query(array_merge(array(‘locale’=>$this->locale), $params));
    $context = $this->createRequestContext($url, $method, $content);
    return json_decode(file_get_contents($url, false, $context));
    }

    and i am calling the
    $create_new_folder = $dropbox->CreateFolder(‘/’.$foldername);

    but it doesn’t create the folder nor it returns any error….
    pls help….

  • sabana says:

    Also i tried the below

    function CreateFolder($dropbox_path)
    {
    $url = $this->cleanUrl(self::API_URL.”fileops/create_folder”);
    $content = ‘locale=’.$this->locale.’&root=’.$this->rootPath.’&path=’.$dropbox_path;
    $context = $this->createRequestContext($url, “POST”, $content);
    return json_decode(file_get_contents($url, false, $context));

    }

    but no success.

  • Fabi says:

    sabana, your approach seems to be correct, however there was a bug in DropPHP.
    Get the latest version 1.1 https://fabi.me/download/scripts/DropPHP.zip
    It has some fixes and includes new functions GetLink, Delta, Copy, CreateFolder, Delete, Move .

    Please report if that’s working now.

  • Daniel says:

    seems to work perfectly!
    thank you man! 😀

  • Denys says:

    Hi! If I call “$dropbox->GetAccountInfo()” , I have in my case error

    “Warning: file_get_contents(https://api.dropbox.com/1/account/info): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in /home/dan/WEB/www/uwcIII-dev.my/lib/Social/DropPHP/DropboxClient.php on line 346 NULL “

  • mega says:

    UploadFile ist wohl 1. kaputt und 2. die Variable unlogisch benannt.
    Gefühlt muss dort als $dropbox_path der Pfad inkl Dateiname angegeben werden.
    Am Dateiname hängt dann aber ?overwrite=1&locale=en .
    Ist $dropbox_path nur der Pfad ohne Dateiname, heißt die Datei dann einfach nur ‘?overwrite=1&locale=en’
    In der sample.php fehlt der $dropbox_path komplett. Dadurch entsteht eine Datei, auch mit ?overwrite=1&locale=en am Dateiname.

    Ich hoffe mal, das Problem ist leicht lösbar.
    Ansonsten schon mal tolle Sache, nur muss die in PHP eingelesene und bearbeitete Datei auch wieder in die Dropbox zurück kommen.

  • Fabi says:

    mega, da hast du Recht. Ich werd mir das mal die Tag anschauen.

  • Kai says:

    Ich habe eine Exception beim Autorisieren.
    — ‘DropboxException’ with message ‘Could not get request token! —
    (sample.php) Zeile 49: BuildAuthorizeUrl
    => (DropboxClient.php) Zeile 87: GetRequestToken;
    => (DropboxClient.php) Zeile 51: authCall;
    => (DropboxClient.php) Zeile 335: createRequestContext;
    In der Funktion AuthCall ist $data leer. Ich habe nach parse_str einen print_r($data) gemacht und bekomme nur ein leeres Array angezeigt.

    Muss ich meinen Server noch entsprechend konfigurieren, damit der Dropbox-Zugriff funktioniert?

  • Ryan says:

    Downloading and uploading file methods don’t show anything. I am trying to download and upload an image to/from dropbox but I don’t get anything returned from printing out. Am I missing something?

  • Arsalan says:

    I’m having problem in uploading file in a particular Linux-based server. The script is running perfectly on some other Windows and Linux servers but in one Linux server, UploadFile() function is doing nothing (not even giving any error). New folder is successfully created in my Dropbox account but no file is getting uploaded. What might be the cause for it?

  • I have the same issue as Denys, above:

    Warning: file_get_contents(https://api.dropbox.com/1/account/info) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in /home/ugandaradio/www/sandbox/DropPHP-master/DropboxClient.php on line 348

    This means that file_get_contents is banned from using dropbox, no?

    Would this mean that cURL would work instead? But… how to rewrite the code for cURL?

  • Daniel says:

    Hi
    I’d be amazing if u upload an example of a uploading test. I’m sure that you’ll help many people with that.
    Greetings and thanks!

  • Fabi says:

    Hello all,

    just uploaded Version 1.2:
    – Fixed query string parameters issues
    – Added GetLink() to sample.php
    – UploadFile fixed
    – Decreased buffer size

    Upload should work now.

    Daniel, there is an upload test in sample.php

  • JacobJensen says:

    Hi, I’m not good at php… could you supply an example of a upload form using your class? This would help a lot of us dummies in the world 😉

  • JacobJensen says:

    Sweet! Thank you!!

    In your comments in the code, you mention that I’m supposed to replace the token part with my own… What do you mean? Is yours unsecure or something (got no clue how-to put in my own) 🙂

  • Gabriel C says:

    In some websites I’m getting the following errors of Request token not found.
    Other warnings : Undefined index: oauth_token_secret, oauth_token

  • madhu says:

    It’s working good. And i need a small help from you.

    –>I am able get photos of the user from his/her Dropbox using your api.
    –> I want to get thumbnails from the user Dropbox. How can i get those thumbnails.

    Can you please send me the solution to my mail.
    My Email id: madhu54108@gmail.com

    Regards,
    Madhu.

  • Dekel Maman says:

    Hi
    I can’t get it work, i’m getting error:

    Warning: file_put_contents(tokens/so1z58kvj62w7tz.token) [function.file-put-contents]: failed to open stream: No such file or directory in /home/content/82/8781982/html/magnet/dropbpx/DropPHP/sample.php on line 81
    Authentication required. Click here.

    anyhelp ???

1 2 3 4

Leave a Reply

Your email address will not be published. Required fields are marked *