Php curl login with csrf token

有些话、适合烂在心里 提交于 2021-01-27 19:48:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!