Home > Programming > Mimic a Login with CURL

Mimic a Login with CURL

Maybe this concept is much easier for others, but I had a hard time figuring out how to properly use CURL and PHP to mimic a login.  I’ll go ahead and post the code and then describe how you can figure out exactly what you should be doing to mimic a website’s login process:

<?
$ch = curl_init();

// Let's set the URL of where we want the form to POST to
curl_setopt($ch, CURLOPT_URL, 'http://www.somewebsite.com/login');

// Set the referring page
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somewebsite.com");

// Make sure we enable the POST
curl_setopt ($ch, CURLOPT_POST, 1);

// Set the parameters for the POST fields
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'action=login&user=Someuser&password=Somepassword&submit=Login');

// This is the key line here.  This will mimic a cookie on our machine, but instead
// will save it to the local directory of this script in a cookie.txt file.
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

// We don't want it to print out the results for this, so set
// this option to 1
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute our login request
curl_exec ($ch);

// Now we should be able to go wherever we want since we've mimiced a login
// by using curl and a 'cookie.txt' cookie jar file
$target_url = "http://www.website.com/the_page_we_want_to_visit_after_login.php";
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_exec($ch);
?>

To figure out what pages to visit and exactly what items were being posted to the above page, I used a nice plugin for Mozilla called LiveHTTPHeaders.  The easiest way to detect all of the URL’s, POST’ed variables, and any other checks that a login process does is to use this add-on to capture all of that information and then mimic it with the CURL functions above.  You should be able to login and then roam around freely with your usual credentials, thanks to our cookie.txt file, which will look something like:

# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

.somewebsite.com	TRUE	/	FALSE	0	PHPSESSID	9c78c16ef63ad3cb2cd9f1d00466c319
.somewebsite.com	TRUE	/	FALSE	1276117626	isAuthorized	Y

I hope someone else finds this useful!

Categories: Programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.