1

I am trying to extract the CSRF-token from a website to enable auto-login for my members on that page through credentials that I am sending via a POST-request. Unfortunately, that token is contained in the value of a hidden input field with the name "__csrf_token".

I have used the following code to successfully extract the value of the input field with the name "email", however when I use it on the above mentioned token field it just doesn't return a value.

<?php

$ch = curl_init("https://www.example.com/login.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
$response = curl_exec($ch);

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($response);
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
    $grab = $tags->item($i);
    if($grab->getAttribute('name') === '__csrf_token') {
        $token = $grab->getAttribute('value');
    }
}
echo $token;
?>

Do you have any idea why the search for the mentioned name doesn't return a value?

Thanks! (Edit: Typo)

Tim
  • 43
  • 5
  • @Barmar: Of course, sorry. That was a typo from the code I copied, still not working. – Tim Oct 28 '20 at 20:28
  • Maybe unrelated to the problem, but you should break out of the loop once it gets the token. – Barmar Oct 28 '20 at 20:30
  • What problem are you having? Is it not finding the hidden input, or is it finding the input but not getting the value? Are you sure the value is in the HTML, rather than added dynamically with JavaScript? – Barmar Oct 28 '20 at 20:32
  • @Barmar: That's a good point. When I view the page with GoogleDevMode I can see the hidden input field, however, as soon as I curl it the curl output does not contain it. Is there any way to get the complete html with the (probably) js-generated code with curl? – Tim Oct 28 '20 at 20:34
  • 1
    https://stackoverflow.com/questions/199045/is-there-a-php-equivalent-of-perls-wwwmechanize – Barmar Oct 28 '20 at 20:38
  • @Barmar Thanks a lot for your input! The implementation needs to work on a wordpress page later on...any recommendations on which of the tools mentioned would be best suitable? – Tim Oct 28 '20 at 20:46
  • http://simpletest.sourceforge.net/en/browser_documentation.html is a PHP library that you can load into the wordpress page. – Barmar Oct 28 '20 at 20:48
  • @Barmar Thank you very much! I will take a look at it. Might take a while to figure it out though. – Tim Oct 28 '20 at 20:59

0 Answers0