如何通过php在外部web中启动会话



我正试图通过php和curl登录到一个外部页面,但我对此并不熟悉。

这是我的代码:

<?php 
$username = ".........@gmail.com";
$password = "........";

$url = "https://lobby.ikariam.gameforge.com/login.php";
$cookie= "c:\cookies.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) die(curl_error($ch));
$dom = new DomDocument();
$dom->loadHTML($response);
$tokens = $dom->getElementsByTagName("meta");
for ($i = 0; $i < $tokens->length; $i++)
{
$meta = $tokens->item($i);
if($meta->getAttribute('name') == 'csrf-token')
$token = $meta->getAttribute('content');
}
$postinfo = "email=".$username."&password=".$password."&_csrf=".$token;
echo $token; //debug info
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
$html = curl_exec($ch);
print($html);
if (curl_errno($ch)) print curl_error($ch);
curl_close($ch);
?>

但当我尝试时,我给出了这个错误:

注意:未定义的变量:第25行C:\examplep\htdocs\Ikariam\index.php中的token

注意:第26行C:\examplep\htdocs\Ikariam\index.php中的未定义变量:token405不允许nginx/1.16.11

在循环之前定义$token并搜索,直到找到所需的令牌:

$token = '';
for ($i = 0; $i < $tokens->length; $i++)
{
$meta = $tokens->item($i);
if ($meta->getAttribute('name') == 'csrf-token') {
$token = $meta->getAttribute('content');
break; // exit the loop if the token is found
}
}

当然,您需要确保在$tokens数组中有一个csrf-token

希望这会有所帮助。

最新更新