Skip to content
Advertisement

Want to get the CSRF Token from this text in CURL PHP

I’m trying to get the CSRF token from raw text, basically, I have a lot of text data on PAGE, I have almost 5-10 CSRF tokens on that page all are the same, I just want to grab one csrf token from text and save into in PHP variable.

<?php

$url = "--";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
preg_match_all('/^x-csrf-token:s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);      
 
}   
$session = $cookies['x-csrf-token'];
echo($session);


?>

Here is the code but it’s not working.

TEXT Screen: enter image description here

Advertisement

Answer

Your regex doesn’t seem related to your sample text.

Specifically:

  • the ^ character matches the start of your text, while your matches are within the text. So this needs to be removed
  • you’re missing the encasing quotes ' which are in the original text
  • you’re matching [^;]* which means to interrupt when you find a semicolon, but there’s no semicolon in your text

Based on the sample text you shared the regex should be

/x-csrf-token',s*'([^']+)/mi

3v4l example: https://3v4l.org/WjKhb

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement