views:

1065

answers:

3

Hi,

imagine the following scenario: I open a CURL connection and pass some XML-Logindata via POST. The server answers with an 302 redirect, where the session cookies are set and redirects me to a following "welcome"-page. If I enable FOLLOWLOCATION the cookies set on the redirection-page get lost and the welcome-page fails with a "session expired"-message. If I disable FOLLOWLOCATION, I'm not redirected (obviously) and get a HTML-page with "the page has moved to another location" with a link that leads me to the welcome-page. This works as the cookies are set, but I need to follow the redirect and go straight to the welcome-page.

So, how do I maintain the cookies so that they are set correctly?

This is my code so far:

$ch = curl_init('https://www.example.com/login');

curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '<some xml data>');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml; charset=UTF-8"));

url_exec($ch);
curl_close($ch)

Thanks for any help! ;

+3  A: 

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;

}
acme
+1  A: 

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 stored
curl_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

Gabriel Braila
Thanks! I'll give it a try.
acme
+1  A: 

You might want to check out this library too: http://github.com/shuber/curl

Sean Huber
Thank you. I'll give it a try!
acme