使用PHP和cURL提供下载 [英] Serving downloads with PHP and cURL

查看:179
本文介绍了使用PHP和cURL提供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,使用我的Megaupload溢价帐户为用户提供下载。这是我用来下载Megaupload文件的方法:

I am writing a script that serves users downloads using my Megaupload premium account. This is the method that I'm using to download the Megaupload files:

public function download_file($link)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies/megaupload.txt");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    return curl_exec($ch);
    curl_close($ch);
}

这是如何在index.php中调用:

And this is how it's being called in index.php:

readfile($megaupload->download_file("http://www.megaupload.com/?d=PXNDZQHM"));

我基本上想做的是将下载内容提供给用户, 。我不想将文件保存到我的服务器,然后提供给用户。

What I basically want this to do is serve the download to the user and stream the download through my server. I do not want the file to be saved to my server and then offered to the user.

但显然,上述解决方案不会工作。我收到此错误:

But obviously, the solution above won't work. I get this error:

Warning: readfile() [function.readfile]: Filename cannot be empty in C:\xampp\htdocs\index.php on line 8



我需要使用cURL,因为我需要请使用cookie文件(/cookies/megaupload.txt)请求下载。

I need to use cURL for this because I need to request the download using a cookie file (/cookies/megaupload.txt).

任何人都可以想到一种工作方式来做到这一点? Cheers。

Can anyone think of a working way to do this? Cheers.

推荐答案

是的,正如它所说, readfile 文件名,你给它一个curl结果的字符串。只需在设置适当的标题后使用echo:

Yes, exactly as it says, readfile expects a filename, and you're giving it a string of the curl result. Just use echo after setting the proper headers:

echo $megaupload->download_file("http://www.megaupload.com/?d=PXNDZQHM");

EDIT 一些基本检查你得到的东西:

EDIT: Also you need to do some basic checks that you got something back:

public function download_file($link)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies/megaupload.txt");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    // close before you return
    curl_close($ch);
    return $result;
}

然后:

$filecontents = $megaupload->download_file("http://www.megaupload.com/?d=PXNDZQHM");
if($filecontents) {
  echo $filecontents;
}
else {
  die("Yikes, nothing here!");
}

这篇关于使用PHP和cURL提供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆