How do I pass cookies on a CURL redirect? How do I pass cookies on a CURL redirect? curl curl

How do I pass cookies on a CURL redirect?


This is an old question, but I had the same problem, so google took me here.Finally, I managed to solve it.By passing an empty string "" to set CURLOPT_COOKIEFILE using curl_setopt will solve the problem:

curl_setopt($ch, CURLOPT_COOKIEFILE, "");

See section CURLOPT_COOKIEFILE of http://curl.haxx.se/libcurl/c/curl_easy_setopt.html


to instruct php on curl session to use cookies you should set two options:

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');// set where cookies will be storedcurl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');// from where it will get cookies

so every cookie will be appended on CURLOPT_COOKIEJAR and those cookie will be carried on every location by setting CURLOPT_COOKIEFILE


To answer myself, this is how I did it:

Grab the header-http-status code. If it's redirect then extract the new location and redirect manually. Otherwise remove the header and output the contents:

$response = curl_exec($ch);$info = curl_getinfo($ch);curl_close($ch);if($info['http_code'] == 301 || $info['http_code'] == 302) { // redirect manually, cookies must be set, which curl does not itself    // extract new location    preg_match_all('|Location: (.*)\n|U', $response, $results);    $location = implode(';', $results[1]);    // redirect manually    header("Location: $location");    exit;} else { // no redirect, remove header and output directly    $response = substr_replace($response, '', 0, strpos($response, '<', 0));    echo $response;}