PHP cURL Authentication Issue PHP cURL Authentication Issue curl curl

PHP cURL Authentication Issue


Authentication fails due to the mismatch between token and cookie(s) passed.

When you load the page to retrieve the token with get_token() the server is sending you a cookie that you are not saving.

Later when you try to login the server expects to receive same cookie it sent you when you got the token. But you're not sending it.

I suggest you to the rewrite get_token() using curl and storing cookies in cookie.txt. This will let you pass them later when you'll call login()

Like this:

function get_token() {    $url = 'https://www.foo.com/';    $curl = curl_init();    curl_setopt($curl, CURLOPT_URL, $url);    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);    curl_setopt($curl, CURLOPT_COOKIEJAR, "cookie.txt");    curl_setopt($curl, CURLOPT_COOKIEFILE, "cookie.txt");    curl_setopt($curl, CURLOPT_TIMEOUT, 40000);    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);    $result = curl_exec($curl);    curl_close($curl);    unset($curl);    $html = str_get_html( $result );    $token = "";    foreach($html->find('input') as $element) {        if($element->name == "token") {            $token = $element->value;        }    }    if (!$token) {        die('No token found');    }    return $token;}

Important:

Remove

$fp = fopen("cookie.txt", "w");fclose($fp);

From login() as that truncates to zero bytes the cookie.txt file, and you don't want to delete the cookie just retrieved.

Note that curl_exec() creates the speciefied cookie file if it doesn't exist.