Login via PHP cURL

Here is a nice little snippet that allows you to log in to a web form and then proceed to another page to get Dynamically generated files.

First you must create a file in tmp or any directory you choose and make sure it is writable for making your cookie.

$login = "https://domain.com/login.php";
$url = "https://domain.com/statistics.php";
 
$cookie = "/tmp/domain.txt";
$reffer = "https://domain.com/login.php";
 
// these are were we write our data to locally
$logfile = "domain.log.1"; // first file to create
$logdir="logs";
 
// are query strings. this is an array but you can set up to pull from a database if needed
 
$query = array(1=>"UserServiceId=1111&Action=CSV",
		"UserServiceId=1112&Action=CSV",
		"UserServiceId=1113&Action=CSV");
 
//login page
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $login);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
// Action is set because this paticular form needs it to process to the next page
curl_setopt($ch, CURLOPT_POSTFIELDS, "Email=Username&Password=Password&Action=Login"); 
// may differ from form to form, View source of page to see what is needed
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); // get file
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); // write to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // process page
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec ($ch);
 
curl_close ($ch);
 
// now for each query string we cURL
 
foreach($query as $page=>$csv){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $csv); // get file
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$result.= site_name($id).substr(curl_exec($ch), 44); // append data and organize by site name
}
curl_close ($ch);
 
//Error check
if ($result == NULL) { 
           echo "Error: <br />";
           echo curl_errno($ch) . " - " . curl_error($ch) . "<br />";
}
 
development/php/curl_-_php_login_to_https.txt · Last modified: 2007/09/13 19:09 by vincenzobar
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki