fabi.me

DropPHP – simple PHP Dropbox API Client without cURL

VN:F [1.9.22_1171]

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.4 KiB
7179 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 – simple PHP Dropbox API Client without cURL, 4.4 out of 5 based on 13 ratings

Comments

  • Ben says:
    VA:F [1.9.22_1171]
    Rating: +1 (from 1 vote)

    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;
    }

  • nabil says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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!’

  • Fabi says:
    VN:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    Hi nabil & Terrence,

    update to latest version 1.6, this fixes the issue.

  • Stefan says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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).

    • Fabi says:
      VN:F [1.9.22_1171]
      Rating: 0 (from 0 votes)

      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

  • Anthony says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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

    • Fabi says:
      VN:F [1.9.22_1171]
      Rating: 0 (from 0 votes)

      Hi Anthony,

      please try this version: http://fabi.me/download/DropboxClient.zip
      It gives more debug data if download fails.

      • Anthony says:
        VA:F [1.9.22_1171]
        Rating: +1 (from 1 vote)

        Thanks Fabi. I will try this out.

      • Anthony says:
        VA:F [1.9.22_1171]
        Rating: 0 (from 0 votes)

        Hi Fabi,

        This is what I got from the updated DropboxClient file that you gave.

        Thanks and regards,
        Anthony

        • Anthony says:
          VA:F [1.9.22_1171]
          Rating: 0 (from 0 votes)

          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] =>

        • Fabi says:
          VN:F [1.9.22_1171]
          Rating: 0 (from 0 votes)

          Can you post the DownloadFile call including the parameters you are passing?

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            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

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: +1 (from 1 vote)

            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

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            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”

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            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’)

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            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

          • Fabi says:
            VN:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            Anthony, have you tried SetUseCUrl(true/false) ?

          • Anthony says:
            VA:F [1.9.22_1171]
            Rating: 0 (from 0 votes)

            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

  • FOXRULE says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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!

  • zoe says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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

  • VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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?

  • VA:F [1.9.22_1171]
    Rating: +1 (from 1 vote)

    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

  • Jums says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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!

    • Jums says:
      VA:F [1.9.22_1171]
      Rating: 0 (from 0 votes)

      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

  • Glenn says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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

  • VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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?

  • Hiren Raiyani says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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!

  • ilovepie says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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 [...]

  • Michael says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    Hi Fabi,

    good Job, thank you.
    Can you tell me, how i can get the process of a file during the download?

    Thanks Michael

  • John Doe says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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 ?

  • John Doe says:
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

    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 ?

1 2 3

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>