问题
I want to simulate login with curl in php with csrf token. I know the token is refreshed every session and I need to use the same cookie and I do it like this:
<?php
use Symfony\Component\DomCrawler\Crawler;
require 'vendor/autoload.php';
function login($url,$data){
$login = curl_init();
curl_setopt($login, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($login, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($login, CURLOPT_TIMEOUT, 40000);
curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($login, CURLOPT_URL, $url);
curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($login, CURLOPT_POST, TRUE);
curl_setopt($login, CURLOPT_POSTFIELDS, $data);
ob_start();
return curl_exec ($login);
ob_end_clean();
curl_close ($login);
unset($login);
}
function grab_page($site){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, $site);
ob_start();
return curl_exec ($ch);
ob_end_clean();
curl_close ($ch);
}
// Grab the page with the csrf_token
$signinPage = grab_page('https://bitbucket.org/account/signin/');
$crawler = new Crawler($signinPage);
$csrf = $crawler->filter('input[name=csrfmiddlewaretoken]')->first();
$csrf = $csrf->attr('value');
login('https://bitbucket.org/account/signin/', ['next' => '', 'csrfmiddlewaretoken' => $csrf, 'username' => 'myemail', 'password' => 'mypass']);
var_dump(grab_page("https://bitbucket.org/site/oauth2/authorize?client_id=my_client_id&response_type=code"));
But it still does not login correctly. Where am I wrong ?
来源:https://stackoverflow.com/questions/49625338/php-curl-login-with-csrf-token