Vũ Nhật Anh
Vũ Nhật Anh

Reputation: 512

Can't keep session ID via CURL PHP

I'm writing a function to fetch the captcha, of course it needs to keep the session. I'm using cookie file for curl and use it for every request but it does not work. When I view the cookie file, I see that the PHPSESSID changed each time I call the function. How could I solve it?

Here is my code

<?php    
function fetch_captcha($url, $cookie_file = false, $user_agent = DEFAULT_USER_AGENT, $timeout = 10) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    if ($cookie_file) {
        curl_setopt($curl, CURLOPT_COOKIESESSION, true);
        curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
    }
    curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);

    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Upvotes: 1

Views: 2218

Answers (1)

Barmar
Barmar

Reputation: 780909

Don't use:

curl_setopt($curl, CURLOPT_COOKIESESSION, true);

PHPSESSID is a session cookie, and this option causes each cURL call to start a new session, so it ignores all session cookies in the file.

Upvotes: 1

Related Questions