从共享网址下载带有 PHP + curl 的 Dropbox 文件


Download Dropbox File with PHP + curl from share URL

我用 curl 用 PHP 编写了以下代码,试图下载用户以单独的 POST 表单提供的远程文件(从 Dropbox )。当我使用任何其他服务器作为文件的原始主页时,例如我自己的服务器,下载工作正常,文件完整(从不同的 SE 线程中了解到这一点)。所以我知道我的代码至少可以执行我告诉它的任务。

但是,Dropbox似乎存在一些问题,因为无法打开从其服务下载的任何文件。

您无法在代码中看到它,但 Dropbox Share URL 在末尾添加了所需的"?dl=1"(迫使我们遵循重定向)。

这是否与Dropbox拥有的SSL证书或API有关,如果是这样,有没有办法绕过curl的检查?

目标是允许用户使用私人表单发布他们的共享 URL,并自动下载文件,所以我不确定使用 Dropbox 的 API 进行身份验证会有所帮助,因为这需要对每个用户进行身份验证(这对他们来说太复杂了)。

<?php
var_dump($_POST);
$fileurl = $_POST['file'];
$path_parts = pathinfo($fileurl);
$filebase = $path_parts['basename'];
$filename = $path_parts['basename'];
$filepath = 'files/tmp/'.$filebase;
# start curl
$ch = curl_init();
# open file to write
$fp = fopen($filename, 'w+b');
curl_setopt( $ch, CURLOPT_URL, $fileurl );
# set return transfer to false
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
# increase timeout to download big file
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
# write data to local file
curl_setopt( $ch, CURLOPT_FILE, $fp );
# execute curl
curl_exec( $ch );
# close local file
fclose( $fp );
# close curl
curl_close( $ch );
$curl = curl_init();
$postfields = "file=$filepath&sfname=$filename";
curl_setopt($curl, CURLOPT_URL,"url_goes_here");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec ($curl);
curl_close ($curl);
?>

提前谢谢。

这有点黑客,有点对我有用:

function getDropboxDownloadURL($url) {
  // create curl resource 
  $ch = curl_init(); 
  // set url 
  curl_setopt($ch, CURLOPT_URL, $url); 
  //return the transfer as a string 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  // $output contains the output string 
  $content = curl_exec($ch); 
  // close curl resource to free up system resources 
  curl_close($ch);      
  // http://stackoverflow.com/questions/3820666/grabbing-the-href-attribute-of-an-a-element
  $dom = new DOMDocument;
  $dom->loadHTML($content);
  foreach ($dom->getElementsByTagName('a') as $node) {
    $url = $node->getAttribute('href');
    // or you can check other conditions
    if (startsWith($url, "https://www.dropbox.com")) {
        return $url;
    }
  }
}

输入 url 为"https://www.dropbox.com/s/m0cw695klan1dz1/running_men.jpg.zip?dl=0",输出为 "https://www.dropbox.com/s/m0cw695klan1dz1/running_men.jpg.zip?dl=1"