使用PHP curl和CSRF令牌登录 [英] Login with PHP curl and CSRF token

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

问题描述

我想从PHP脚本登录到另一个网站,但我总是得到这个回复:

I want login from a PHP script to another website but I always get this reply:

403 Error: CSRF token mismatch

我从网站上的隐藏字段提取CSRF令牌,但似乎是错误的。这是我的代码:

I extract the CSRF token from a hidden field on website but it seems it is wrong. This is my code:

$username = "testuser";
$password = "testpass";

$path = "c:\\test\\";
$url="http://itw.me/login";

$field='_csrf';
$html=file_get_contents( $url );

libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->validateOnParse=false;
$dom->recover=true;
$dom->formatOutput=false;
$dom->loadHTML( $html );
libxml_clear_errors();
$xpath=new DOMXPath( $dom );
$col=$xpath->query('//input[@name="'.$field.'"]');
foreach( $col as $node ) $csrftoken=$node->getAttribute('value');
echo "-".$csrftoken."-";

$postinfo = "email=".$username."&password=".$password."&_csrf=".$csrftoken;
$cookie_file_path = $path."/cookie.txt";

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, "http://itw.me");
$html = curl_exec($ch);
print($html);
curl_close($ch);


推荐答案

c> file_get_contents 和您使用cURL的第二个请求。

You are making your first request with file_get_contents and your second request with cURL.

您为第二个请求设置了一个cookie jar,请求。因此,这两个请求中的每一个都开始一个新的会话。

You've set up a cookie jar for the second request, but not for the first request. Consequently, each of those two requests is starting a new session.

CSRF令牌由您发出请求的服务器存储在会话中,因此您获得的令牌第一个请求将不会与第二个请求的会话中的令牌匹配。

CSRF tokens are stored in the session by the server you are making the request to, so the token you get the first request won't match the token in the session for the second request.

您需要:


  • 一起使用cURL

  • 对这两个请求使用相同的cookie jar

这篇关于使用PHP curl和CSRF令牌登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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