You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求基于Dropbox Version 2 API的PHP文件上传表单代码方案

Hey there! I’ve put together a complete PHP implementation for file uploads using the Dropbox Version 2 API, including both the frontend form and backend API interaction logic. Before we jump into the code, let’s cover the prerequisites to make sure everything works smoothly.

Prerequisites
  • Sign up for a Dropbox Developer account and create a new app (choose "Scoped access" and the appropriate access type for your use case)
  • Generate a Scoped Access Token for your app, and ensure you’ve granted the files.content.write permission (this is required to upload files to Dropbox)
  • Make sure your PHP environment has the cURL extension enabled (most shared hosting and local dev environments have this enabled by default)
1. Frontend Upload Form (upload_form.php)

This is a simple, user-friendly HTML form that lets users select a file to upload, with status feedback after submission:

<!DOCTYPE html>
<html>
<head>
    <title>Dropbox File Upload</title>
    <style>
        .container { max-width: 500px; margin: 2rem auto; padding: 0 1rem; }
        .upload-form { padding: 2rem; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .form-group { margin-bottom: 1.5rem; }
        label { display: block; margin-bottom: 0.5rem; font-weight: 500; }
        input[type="file"] { padding: 0.5rem; border: 1px solid #ddd; border-radius: 4px; width: 100%; }
        .btn { padding: 0.75rem 1.5rem; background: #0061ff; color: white; border: none; border-radius: 4px; cursor: pointer; transition: background 0.2s; }
        .btn:hover { background: #0047cc; }
        .alert { padding: 1rem; border-radius: 4px; margin-top: 1rem; }
        .alert.success { background: #e8f5e8; color: #2e7d32; }
        .alert.error { background: #ffebee; color: #c62828; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Upload File to Dropbox</h1>
        
        <?php if (isset($_GET['status'])): ?>
            <?php if ($_GET['status'] === 'success'): ?>
                <div class="alert success">File uploaded successfully to Dropbox!</div>
            <?php else: ?>
                <div class="alert error">Error: <?php echo htmlspecialchars($_GET['message']); ?></div>
            <?php endif; ?>
        <?php endif; ?>

        <form class="upload-form" action="upload_handler.php" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="file">Select File:</label>
                <input type="file" id="file" name="file" required>
            </div>
            <button type="submit" class="btn">Upload to Dropbox</button>
        </form>
    </div>
</body>
</html>
2. Backend API Handler (upload_handler.php)

This script handles the file upload, interacts with the Dropbox V2 API, and redirects back to the form with clear status messages:

<?php
// Configuration - Replace with your Dropbox Scoped Access Token
// For production, use environment variables instead of hardcoding!
$DROPBOX_ACCESS_TOKEN = 'YOUR_SCOPED_ACCESS_TOKEN_HERE';

// Check if a file was uploaded without errors
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    header('Location: upload_form.php?status=error&message=No file uploaded or upload error occurred');
    exit;
}

$uploadedFile = $_FILES['file'];
$fileName = $uploadedFile['name'];
$fileTmpPath = $uploadedFile['tmp_name'];
$fileSize = $uploadedFile['size'];

// Optional: Add file size validation (example: max 10MB)
$maxFileSize = 10 * 1024 * 1024; // 10MB
if ($fileSize > $maxFileSize) {
    header('Location: upload_form.php?status=error&message=File size exceeds 10MB limit');
    exit;
}

// Read uploaded file content
$fileContent = file_get_contents($fileTmpPath);
if ($fileContent === false) {
    header('Location: upload_form.php?status=error&message=Failed to read uploaded file');
    exit;
}

// Dropbox API endpoint for direct file upload
$apiUrl = 'https://content.dropboxapi.com/2/files/upload';

// API request headers
$headers = [
    'Authorization: Bearer ' . $DROPBOX_ACCESS_TOKEN,
    // Configure upload parameters: path, mode, autorename, etc.
    'Dropbox-API-Arg: {"path": "/' . rawurlencode($fileName) . '", "mode": "add", "autorename": true, "mute": false}',
    'Content-Type: application/octet-stream'
];

// Initialize cURL session
$ch = curl_init($apiUrl);

// Set cURL options for secure API call
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Enable SSL verification for security

// Execute request and get response
$response = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Handle cURL errors
if (curl_errno($ch)) {
    $errorMessage = curl_error($ch);
    curl_close($ch);
    header('Location: upload_form.php?status=error&message=cURL Error: ' . htmlspecialchars($errorMessage));
    exit;
}

curl_close($ch);

// Process API response
if ($httpStatusCode === 200) {
    // Upload successful
    header('Location: upload_form.php?status=success');
    exit;
} else {
    // Parse Dropbox's error response
    $errorData = json_decode($response, true);
    $errorMessage = $errorData['error']['summary'] ?? 'Unknown error occurred during upload';
    header('Location: upload_form.php?status=error&message=' . htmlspecialchars($errorMessage));
    exit;
}
?>
Important Notes
  • Never hardcode your access token in the script! For production use, store it in an environment variable (e.g., getenv('DROPBOX_ACCESS_TOKEN')) or an encrypted configuration file to avoid security risks.
  • This implementation works for small files (up to 150MB, per Dropbox API limits). For larger files, you’ll need to use Dropbox’s upload session API (split the file into chunks, upload each chunk, then commit the session).
  • Add additional validation (file type checks, sanitize file names) to prevent malicious uploads. For example, restrict allowed MIME types or file extensions.
  • The mode parameter in the Dropbox-API-Arg header is set to add (creates a new file or renames it if a duplicate exists). You can change this to overwrite to replace existing files, or update for specific file revisions.
  • We use htmlspecialchars() to sanitize error messages before displaying them, which prevents cross-site scripting (XSS) attacks.

内容的提问来源于stack exchange,提问作者Ravi Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:42:43