PHP Curl登录论坛但不会保持登录状态?

时间:2010-11-23 03:53:31

标签: php

我正在尝试从私人论坛中提取一些数据。我创建了一个使用CURL登录的PHP脚本,以及DOMDocument来提取页面数据。

我已成功使用该脚本登录,但是当我尝试使用loadHTMLFile()加载网页时,它就好像我从未登录过一样。

有人告诉我,我可能需要发送Cookie标头?但我不知道该怎么做或者甚至是必要的。

有人有什么想法吗?

    <?
function vBulletinLogin($user, $pass)
{
       $md5Pass = md5($pass);
       $data = "do=login&url=index.php&vb_login_md5password=$md5Pass&vb_login_username=$user&cookieuser=1";
       $ch = curl_init();

        curl_setopt ($ch, CURLOPT_URL, "****"); // replace ** with tt
        curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
        curl_setopt ($ch, CURLOPT_TIMEOUT, '10');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_COOKIEJAR, "/public_html/phpcrawl/cookies.txt");
        curl_setopt($ch, CURLOPT_COOKIEFILE, "/public_html/phpcrawl/cookies.txt");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERRER, "****"); 
        $store = curl_exec ($ch);
        echo $store; <- **this shows that I have successully logged in, it gives me a welcome message**
        print_r($_COOKIE);

        curl_close($ch);

       $pos = strpos($store, "Thank you for logging in");
       if($pos === FALSE) RETURN 0;
       else RETURN 1;

}
if(vBulletinLogin("****","****")) echo "Logged In";
else echo "Failed to Login check User / Pass";

$url="http://texturl.com";
echo $url."<br>";

//get new HTML document
$html = new DOMDocument(); 

$html->loadHTMLFile($url);
print $html->saveHTML(); <- shows a login and password box saying I am not logged in. 

1 个答案:

答案 0 :(得分:1)

我相信每次获取html页面后都必须使用curl,第一次使用curl登录,这会将登录的cookie保存到其cookie jar中。因此,下次你使用curl(使用相同的cookie jar)它将发布cookie数据,服务器知道你已登录。切换到使用domdocument我不相信会使用curl的cookie jar来说你是登录。

你需要使用curl来获取html,然后你可以将html传递给domdocument并解析它。