Ever wanted to log into a https website which uses cookies and download contents using CURL? This is especially useful for thus who want to create a web-based software where you can download secured information: ie, price list, quantity list, product list etc from a distribution sites. and have it viewable in your own version or copy that to your own sql server.
This is final code which helped me process through:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
<?php
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
// Login page
$url = "https://xxxxxxxxxxxxx.xxxxxxxxxxxxx.net/servlet/BasicServlet";
// STEP 1 INITIAL SITE SETUP
// Set cookies and save cookies in the temp file
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile); // Stores cookies in the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
// STEP 2 LOGIN TO SCANSOURCE SITE
// Set Fields
$fields = array(
'username' => 'xxxxxxxxxxxxx@xxxxxxxxxxxxxx.com',
'password' => 'xxxxxxxxxxxxx',
'SubmitWidget' =>'Login',
);
$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Post login form and follow redirect
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Tells cURL to follow redirects
$output = curl_exec($ch);
// STEP 3 - COMMANDS
//$url = "xxxxxxxxxxxxx.com/something/something/secure/xxxxxxxxxxxxx.php";
$url = "xxxxxxxxxxxxx.com/something/secure/xxxxxxxxxxxxx.php";
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
// SHOW STEP 3 OUTPUT
echo "Test Content: <br>" . $output . "<br><br><br>";
// DEBUG STUFF
print_r(curl_error($ch));
print_r(curl_getinfo($ch));
print_r(curl_errno($ch));
//Close Connection
curl_close($ch);
?>
Recent Comments