tags:

views:

257

answers:

3

how can we maintain session in cURL?

i'am having a code the sends login details of a site and logs in successfully i need to get the session maintained at the site to continue.

here is my code that used to login to the site using cURL

  <?php  
        $socket = curl_init();
        curl_setopt($socket, CURLOPT_URL, "http://www.XXXXXXX.com");
    curl_setopt($socket, CURLOPT_REFERER, "http://www.XXXXXXX.com");
    curl_setopt($socket, CURLOPT_POST, true);
    curl_setopt($socket, CURLOPT_USERAGENT, $agent);
    curl_setopt($socket, CURLOPT_POSTFIELDS, "form_logusername=XXXXX&form_logpassword=XXXXX");
    curl_setopt($socket, CURLOPT_COOKIESESSION, true);
    curl_setopt($socket, CURLOPT_COOKIEJAR, "cookies.txt");
    curl_setopt($socket, CURLOPT_COOKIEFILE, "cookies.txt");
    $data = curl_exec($socket);
    curl_close($socket); 
   ?>
A: 

Use session_start() function .

pavun_cool
+2  A: 

Since you're referring to a cookies.txt file without any reference to a folder my first guess would be that you're trying to write to a file in a folder that isn't writable. So first check if you actually find a cookies.txt file and if it contains the session cookie(s) you would expect.

wimvds
Thanks for the quick replaythe folder contains cookies.txt file and it is writble with permissions 777
newbie programmer
Is it empty? Curl treats session cookies as non-expiring. If not, try truncating it first. Also you should set the CURLOPT_FOLLOWLOCATION to make sure you complete the login
symcbean
A: 

I would probably move that code into a function. After successful login, you now have the session associated with the cookie you have in your cookie.txt file. On subsequent requests, just keep using that cookie file and you should have a valid session on that site.

Sabeen Malik