Saving and Using Cookies in Curl

If you want to access a page which requires cookies generated from another page, for e.g. to access page b, you need cookies after you login to the login.php page.  Then here is how you can do it using curl.

 

First, pass the login parameters to the login.php page and obtain the cookies and store it in the cookie file using

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);

Then once you have stored the cookie, in the cookie file, use them as follows :

curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);

 

The overall code for the first php file can be designed as follows :

<?php

$url = "http://www.example.com/login.php";
$cookie = "C:/xampp/htdocs/nimish/cookie.txt"; // I was running the code on localhost, and hence the path!
$fields_string = '';
$user = "nimishprabhu";
$pass = "abcd1234";
$submit = "Log in"; // this an actual code, I had used on one of the sites, but the password is fake!
$fields = array(
            'username'=>urlencode($user),
            'password'=>urlencode($pass),
            'Submit'=>urlencode($submit)
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

	$ch = curl_init ($url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
	$output = curl_exec ($ch);
?>

Now once you have got the cookies, the second php file can be coded as follows :

<?php

$url = "http://www.example.com/members_area.php";
$cookie = "C:/xampp/htdocs/nimish/cookie.txt";

$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
?>

If you have any doubts or queries, please post them as comment below or send me an email.

One thought on “Saving and Using Cookies in Curl”

  1. Vincenzo says:

    Hi thanks for you post, i’m going to try if works. I’m trying to login in my website using user credential stored into another server database and the developer has developed a simple api. This generates a unique token for each user. The question is: how do I handle multiple login requests and also how do I attribute this cookie stored in my server to a specific user? Many thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.