Home Ask Login Register

Developers Planet

Your answer is one click away!

brumbrum February 2016

curl: keep cookies while being redirected

I use this code (originally found login into webpage with php with cURL) to first grab the csrf token, create cookie, and than use that csrf token and cookie in a subsequent post request. It doesn't work(deduced from how the final webpage looks) and I think it's because the FOLLOWLOCATION is set to true. It must be set to true, because there are some redirections going on, but redirections also bring the consequence of "misplacing" cookies. The question is..how to keep cookies while being redirected as a response from server.

 $cookie = 'cookies2.txt';

# Initialize a cURL session.
$ch = curl_init('https://example.com/login');

# Set the cURL options.
$options = [
    CURLOPT_COOKIEJAR       => $cookie,
    CURLOPT_USERAGENT => $useragent,


# Set the options
curl_setopt_array($ch, $options);

# Execute
$html = curl_exec($ch);

$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "1.Request sent: $request<br>";

$headerSizeFirst = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headersFirst = substr($html, 0, $headerSizeFirst);
echo "1.Request recieved: $headersFirst";

$dom = pQuery::parseStr($html);
$csrfToken = $dom->query('[name="csrf"]')->val();

 $postData = [
    'csrf'       => $csrfToken,
     'username'       => $email,
     'password'      => $password


 # Convert the post data array to URL encoded string
 $postDataStr = http_build_query($postData);

 $options[CURLOPT_POST] = 1;
 $options[CURLOPT_POSTFIELDS] = $postDataStr;

 $options[CURLOPT_USERAGENT] = $useragent;
 $options[CURLINFO_HEADER_OUT] =>         


Daniel Stenberg February 2016

CURLOPT_COOKIESESSION set to true means you tell libcurl to treat this as a new (cookie) session and it will discard all session cookies at start of a request. You should probably not set that without being really sure that's what you need as it will flush all cookies without a specific expiry date/time.

Otherwise, when the cookie engine has been activated in libcurl it will keep the cookies associated with the handle and reuse them in subsequent requests done with that same handle.

Post Status

Asked in February 2016
Viewed 3,999 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life