Login Using CURL and Maintain Session in PHP Using CURL

Login Using CURL and Maintain Session in PHP Using CURL

To login into a session protected site in PHP using CURL is easy. It is the same as normal data retrieval using CURL with URL and post/get parameters, the only difference is that you will need to specify a cookie file location to save session information. Code example as follows:

	$cookiefile = '/tmp/curl-session';
	$loginUrl = 'http://locahost/test';
	$user = urlencode($username);
	$pass = urlencode($password);

	$ch = curl_init();

	// set URL and other appropriate options
	curl_setopt($ch, CURLOPT_URL, $loginUrl);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&pass=$pass");
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);

	// grab URL and pass it to the browser
	$output = curl_exec($ch);
Now any subsequent request to the same domain URL using the same cookie file will maintain the session until timed out. Happy PHPing.



    1. Eric Lin

      Hi Vincenzo,

      Thanks for visiting my blog. I believe you just need to specify the cookie location the same as the one used by the login, it should work:

      curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

      Can you please give it a try?


Leave a Reply

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

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!