PHP: How to upload a file to Dropbox

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

Dropbox is one of the leading cloud storage services that allows users to save files online and sync them to their devices. Integrating Dropbox’ file upload functionality into your PHP application can create a seamless experience for your users to store their files in the cloud. In this tutorial, we will explore how to upload a file to Dropbox using PHP.

Setting Up

Before we dive into the code, there are a few prerequisites:

  • A Dropbox account
  • Dropbox App with an generated access token
  • Your PHP environment should support cURL

First, visit the Dropbox Developer portal to create a new App. Once created, you will be provided with an access token, which is essential for authentication.

Installation of the Dropbox SDK

Dropbox provides an SDK for PHP that simplifies file interactions. Use composer to install it:

composer require spatie/dropbox-api

Make sure that composer is installed on your system and you’re running the above command in the root directory of your PHP project.

Uploading a File

To upload a file to Dropbox using PHP, we’ll use the SDK mentioned earlier. First, set up an instance of the Dropbox client:

<?php
  use Spatie\Dropbox\Client;

  $client = new Client('YOUR_ACCESS_TOKEN');
?>

Replace ‘YOUR_ACCESS_TOKEN’ with the actual token you obtained from the Dropbox app settings. Now, you’re ready to upload files:

<?php
  $dropboxFile = fopen('/path/to/your/file.txt', 'rb');
  $dropboxPath = '/upload/path/file.txt';

  $uploadedFile = $client->upload(
      $dropboxPath,
      $dropboxFile,
      'add'
  );
  fclose($dropboxFile);

  var_dump($uploadedFile);
?>

This code opens the local file to be uploaded in binary read mode and specifies a path in Dropbox where the file should be uploaded. The ‘add’ parameter ensures that the file will be added and not overwritten if it already exists.

Error Handling

Error handling is crucial when uploading files. You can catch exceptions as follows:

<?php
  try {
    // Previous upload code
  } catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
  }
?>

This will allow you to handle exceptions thrown by the SDK gracefully.

Chunked Uploads

If you’re dealing with large files that exceed the Dropbox upload limits, you’ll need to perform a chunked upload. Here’s how:

<?php
  $source = fopen('/path/to/your/largefile.txt', 'rb');
  $dropboxPath = '/largefile.txt';

  // Start by uploading the first chunk
  $chunkSize = 2 * 1024 * 1024; // 2 MB
  $start = $client->uploadSessionStart(fread($source, $chunkSize));

  // Get the session ID to continue
  $sessionId = $start['session_id'];
  $offset = $chunkSize;

  while (!feof($source)) {
    // Get the next chunk
    $chunk = fread($source, $chunkSize);
    $client->uploadSessionAppendV2($chunk, $sessionId, $offset);
    $offset += $chunkSize;
  }

  // Finish the upload session
  $client->uploadSessionFinish(fread($source, $chunkSize), ['cursor' => ['session_id' => $sessionId, 'offset' => $offset], 'commit' => ['path' => $dropboxPath, 'mode' => 'add']]);

  fclose($source);
?>

This process involves starting a session, repeatedly appending chunks, and then finishing the session. It ensures that the file is uploaded even if it is substantial.

Conclusion

In this tutorial, you’ve learned how to set up the Dropbox SDK in PHP and utilize it to upload files successfully to Dropbox. With proper error handling and mechanisms to deal with large files, you can seamlessly integrate Dropbox file uploading in your PHP applications to enhance user experience and file management capabilities.

Keep in mind that this guide is a simplified version and there are many other aspects such as file sharing, metadata fetching, and file management that you can explore using the Dropbox API and its PHP SDK.