Using the Core API in PHP

The Core API is based on HTTP and OAuth and provides low-level calls to access and manipulate a user's Dropbox account.

If you want to follow along, first register a new app on the App Console. You'll need the app key to access the Core API. Then install the PHP SDK and you'll be ready to go.

Authenticating your app

The Core API uses OAuth 2, but the PHP SDK will take care of most of it so you don't have to start from scratch.

You'll need your API app key and secret, generated for you by Dropbox when you registered your app. The PHP SDK lets you use a JSON file to store your API key and secret separate from your code.

{
  "key": "INSERT_APP_KEY_HERE",
  "secret": "INSERT_SECRET_HERE"
}

Before you can access a user's Dropbox account, you'll need to complete the OAuth 2 authorization flow. For web apps, this is done with the WebAuth class. For this simple command-line example, we'll use the WebAuthNoRedirect class.

# Include the Dropbox SDK libraries
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;

$appInfo = dbx\AppInfo::loadFromJsonFile("INSERT_PATH_TO_JSON_CONFIG_PATH");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");

Now we're all set to start the OAuth 2 flow, which has three parts:

  1. Send the user to the "app approval" page on the Dropbox website.
  2. Receive an "authorization code" from Dropbox.
  3. Convert the authorization code into an access token, which can then be used to make Core API calls.

We first need to send the user to the app approval page. We get the URL for that page by calling the start method.

$authorizeUrl = $webAuth->start();

Next, send the user to $authorizeUrl, which gives them an opportunity to approve your app. If they choose to approve your app, they will be shown an "authorization code".

echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));

Finally, call finish to convert the authorization code into an access token.

list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";

The access token is all you'll need to make API requests on behalf of this user, so you should store it away for safe-keeping (even though we don't for this tutorial). By storing the access token, you won't need to go through these steps again unless the user reinstalls your app or revokes access via the Dropbox website.

To make "real" API calls, construct a Client instance, $accessToken. To test that we've got access to the Core API, try calling getAccountInfo() which will return an Array with information about the user's linked account:

$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);

If you've made it this far, you have a simple app that uses the Core API to link to a Dropbox account and your first API call for account info. Next, we'll upload a file to Dropbox, get its metadata, and then download it back to our app.

Uploading files

Let's say we're building a text editing app and we want to use it to save your latest magnum opus to Dropbox. Let's browse the methods in the PHP docs to see which one will do that for us. This page lists all the methods supported in the SDK. If you scroll down, you'll find uploadFile.

uploadFile takes a path pointing to where we want the file on our Dropbox, and then a file-like object or string to be uploaded there. For this example, let's upload a local copy of working-draft.txt:

$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);

If all goes well, the data in your local working-draft.txt will now be in the root of your app folder (or Dropbox folder, depending on your app's access type). The variable response will be an Array containing the metadata of the newly uploaded file. It will look something like this:

Array
(
    [revision] => 2
    [rev] => 20def95ea
    [thumb_exists] => 
    [bytes] => 354
    [modified] => Sun, 17 Feb 2013 02:06:27 +0000
    [client_mtime] => Sun, 17 Feb 2013 02:06:27 +0000
    [path] => /working-draft.txt
    [is_dir] => 
    [icon] => page_white_text
    [root] => app_folder
    [mime_type] => text/plain
    [size] => 354 bytes
)

Listing folders

If you peruse the various entries in the metadata above, you'll get a good sense for all info we can gather from the file. You can get this info for an entire folder by using the getMetadataWithChildren call.

$folderMetadata = $dbxClient->getMetadataWithChildren("/");
print_r($folderMetadata);

The returned array will list out the files and folders in the path given. It looks something like this:

Array
(
    [hash] => f576eb071486e32a0a3af2e47e8983f9
    [thumb_exists] => 
    [bytes] => 0
    [path] => /
    [is_dir] => 1
    [size] => 0 bytes
    [root] => app_folder
    [contents] => Array
        (
            [0] => Array
                (
                    [revision] => 2
                    [rev] => 20def95ea
                    [thumb_exists] => 
                    [bytes] => 354
                    [modified] => Sun, 17 Feb 2013 02:06:27 +0000
                    [client_mtime] => Sun, 17 Feb 2013 02:06:27 +0000
                    [path] => /working-draft.txt
                    [is_dir] => 
                    [icon] => page_white_text
                    [root] => dropbox
                    [mime_type] => text/plain
                    [size] => 354 bytes
                )

        )

    [icon] => folder
)

In the example above, the app folder root contains the file we just uploaded named working-draft.txt. You'll also see other various but vital bits of information such as the exact location of the file (path), file sizes (bytes), last modified date (modified), and more. If you want to tell if something has changed in the directory, you'll want to store and compare the hash parameter. Similarly, a file's rev parameter tells you if the file has changed. It's useful to keep track of the status of your files, as we'll see in the following example.

Downloading files

Some time has passed and you're ready to start editing that magnum opus of yours again. We'll need the getFile method to download the file.

$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
print_r($fileMetadata);

In addition to writing the file contents into the resource, getFile also returns the file's metadata at its current revision. Every time a change is made to the file, the rev field of the file's metadata changes as well. By saving the revision when you download the file, you'll be able to tell if that file has been updated by another computer or device and choose to download the newer revision of that file.

The complete code

Here's the full source to this guide. Make sure to make a working-draft.txt file exists to get it to work fully. Also remember to insert the path to your JSON config.

<?php

# Include the Dropbox SDK libraries
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;

$appInfo = dbx\AppInfo::loadFromJsonFile("INSERT_PATH_TO_JSON_CONFIG_PATH");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");

$authorizeUrl = $webAuth->start();

echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));

list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";

$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();

print_r($accountInfo);

$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);

$folderMetadata = $dbxClient->getMetadataWithChildren("/");
print_r($folderMetadata);

$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
print_r($fileMetadata);