Login with PHP curl and CSRF token

后端 未结 3 881
忘了有多久
忘了有多久 2021-01-07 02:05

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

403 Error: CSRF token mismatch

I extract the CSRF token from

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 02:26

    now it is working!

    $username = "user";
    $password = "pass";
    $url = "http://url.com/login";
    $cookie= "c:\\cookies.txt";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if (curl_errno($ch)) die(curl_error($ch));
    $dom = new DomDocument();
    $dom->loadHTML($response);
    $tokens = $dom->getElementsByTagName("meta");
    for ($i = 0; $i < $tokens->length; $i++)
    {
        $meta = $tokens->item($i);
        if($meta->getAttribute('name') == 'csrf-token')
        $token = $meta->getAttribute('content');
    }
    $postinfo = "email=".$username."&password=".$password."&_csrf=".$token;
    echo $token; //debug info
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
    $html = curl_exec($ch);
        print($html);
    if (curl_errno($ch)) print curl_error($ch);
        curl_close($ch);
    

提交回复
热议问题