cURL不会返回任何内容

时间:2012-01-20 17:43:33

标签: php curl localhost http-status-code-302

cURL在服务器上没有返回任何内容。一切都适用于localhost,但是当它在远程托管中时,getSearchResults()不返回任何内容(或302标头)。这是服务器配置有问题(试过2个不同)。可以用CURLOPT_FOLLOWLOCATION吗?在localhost上尝试true和false - 仍然有效。在远程托管上,由于某种原因,它不允许关注位置,但如果没有在本地工作,我认为不重要。

<?php
class cURL
{
    private $username;
    private $password;
    private static $tmpfname;

    public function __construct($username,$password) {
        $this->username = $username;
        $this->password = $password;
        $this->makeCookies($username, $password);
    }

    private function makeCookies($username, $password) {
        self::$tmpfname = tempnam("/tmp", "Cookie");
        $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$tmpfname);
        curl_setopt($ch, CURLOPT_COOKIEJAR, self::$tmpfname);
        curl_setopt($ch, CURLOPT_URL,"http://vk.com/login.php");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "email={$username}&pass={$password}");
        ob_start();
        curl_exec($ch);
        ob_end_clean();
        curl_close($ch);
        unset($ch);
    }

    private function getHTML($url){
        $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        curl_setopt($ch, CURLOPT_COOKIEFILE, self::$tmpfname);
        curl_setopt($ch, CURLOPT_COOKIEJAR, self::$tmpfname);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        $contents = curl_exec($ch);
        curl_close($ch);

        return $contents;
    }

    public function getSearchResults($songname) {
        $songname = urlencode($songname); 
        $contents = $this->getHTML("http://vk.com/search?c[section]=audio&c[q]={$songname}");
        return $contents;
    }
}
?>

2 个答案:

答案 0 :(得分:1)

302代码是重定向,因此您需要能够使用CURLOPT_FOLLOWLOCATION从中获取有用的内容。

答案 1 :(得分:0)

对于在安全模式下运行php的Web服务器,Web上有很多重定向机制的实现。例如,here(实际上你应该首先查看它)是我有一天为自己的脚本修改的那个。它可以处理多个重定向,并以您可以轻松理解和修改它的方式编写。