Keeping session alive with Curl and PHP Keeping session alive with Curl and PHP curl curl

Keeping session alive with Curl and PHP


You also need to set the option CURLOPT_COOKIEFILE.

The manual describes this as

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.


You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 


This is how you do CURL with sessions

//initial request with login data$ch = curl_init();curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_COOKIESESSION, true);curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hostscurl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts$answer = curl_exec($ch);if (curl_error($ch)) {    echo curl_error($ch);}//another request preserving the sessioncurl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');curl_setopt($ch, CURLOPT_POST, false);curl_setopt($ch, CURLOPT_POSTFIELDS, "");$answer = curl_exec($ch);if (curl_error($ch)) {    echo curl_error($ch);}

I've seen this on ImpressPages