使用PHP和cURL下载文件

时间:2011-06-14 16:10:24

标签: php curl download

我使用此功能成功下载SWF文件(Flash游戏)。当我在一个特定网站上使用这个脚本时,它会下载所有游戏(我告诉脚本从列表中下载4个游戏),精确大小为299字节?我尝试使用谷歌浏览器下载这些游戏,下载成功。我使用的CURL函数中是否缺少某些内容,或者下载算法不够好?任何帮助将不胜感激。

function saveFlash($fullPaths,$folder,$gamenames,$i){
        $curl = curl_init($fullPaths[$i]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //Create a new file in the given folder
        $fp = fopen($folder."/".$gamenames[$i].".swf", 'w');
            if ($fp == FALSE){ 
                echo "File not opened<br>";} 
        //Ask cURL to write the contents to a file
        curl_setopt($curl, CURLOPT_FILE, $fp);
        //Execute the cURL session
        curl_exec ($curl);
        //Close cURL session and file
        curl_close ($curl);
        fclose($fp);
    }

文本编辑器提供以下内容

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.freeonlinegames.com/">here</a>.</p>
<hr>
<address>Apache/2.2.3 (CentOS) Server at freeonlinegames.com Port 80</address>
</body></html>

2 个答案:

答案 0 :(得分:1)

您需要设置CURLOPT_FOLLOWLOCATION以允许其遵循重定向。

您可能还想设置CURLOPT_MAXREDIRS,以便不会重定向失控。

答案 1 :(得分:1)

您收到的错误是告诉您不允许使用热链接的常见方法。如果您只想下载SWF,则需要设置引荐来源。

curl_setopt($ch, CURLOPT_REFERER, 'http://urlofpagetheswfwasfoundon');

如果之后仍然无效,则可能需要设置适当的用户代理字符串。

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 Something Something');

另外,请确保您被允许做您想做的事情。从别人的网站上删除东西是非常不受欢迎的,而且通常是非法的。