我用PHP编写了以下PHP代码,试图下载一个用户在单独的POST表单中提供的远程文件(来自Dropbox)。当我使用任何其他服务器作为文件的原始主页时,就像我自己一样,下载工作完美,文件是完整的(从不同的SE线程学习)。所以我知道我的代码至少可以用于执行我告诉它的任务。
然而,Dropbox似乎存在一些问题,因为无法打开从其服务下载的任何文件。
您无法在代码中看到它,但Dropbox共享网址已在末尾添加了所需的“?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);
?>
提前致谢。
答案 0 :(得分:0)
这是一个黑客攻击,它对我有用:
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;
}
}
}
输入网址为“https://www.dropbox.com/s/m0cw695klan1dz1/running_men.jpg.zip?dl=0”,输出网址为“https://www.dropbox.com/s/m0cw695klan1dz1/running_men.jpg.zip?dl=1”