How to Login in With Curl and Ssl and Cookies

How to login in with Curl and SSL and cookies

Here is a working example I created from your code. This uses a function getFormFields that I wrote for a similar question (first reference at the bottom of this post) which logs into the Android market.

I think there may have been a couple of things in your script that were preventing the login from working. First, you should urlencode the URL parameters such as email and password in the post string (cURL will not do this for you). Second, I think the x value used as part of the login URL may be required.

Here is a solution that logs in successfully. Note, I re-used the original cURL handle. This is not necessary, but if you specify keep-alive, it will actually re-use the same connection, and it also saves you from having to specify the same options over and over.

Once you have the cookies, you can create a new cURL object and specify the COOKIEFILE and COOKIEJAR and you will be logged in without performing the first steps.

<?php

// options
$EMAIL = 'you@yoursite.com';
$PASSWORD = 'yourpassword';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";


// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['emailAddress'] = $EMAIL;
$fields['acctPassword'] = $PASSWORD;

// get x value that is used in the login url
$x = '';
if (preg_match('/op\.asp\?x=(\d+)/i', $content, $match)) {
$x = $match[1];
}

//$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?x=$x";

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);

// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;


function getFormFields($data)
{
if (preg_match('/(<form action="op.*?<\/form>)/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

function getInputs($form)
{
$inputs = array();

$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);

if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);

if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';

if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

This worked for me, hope that helps get you going.

Here are some other cURL answer I have that may help learn:

  • Retrieve Android Market mylibrary with curl
  • multiple actions with curl
  • sending xml and headers via curl
  • Login to Google with PHP and Curl, Cookie turned off?
  • Pinterest login with PHP and cURL not working

Login to Google with PHP and Curl, Cookie turned off?

Here is some modified code that works.

It first requests the login page to get the initial cookies and extract the required values for the login form. Next it performs a post to the login service. It then checks to see if it is trying to use javascript and meta tags to redirect to the destination URL.

It seemed like you already have code for grabbing the form fields, so I didn't post mine, but if you need it let me know. Just make sure $formFields is an associative array with keys being the field name, and the value being the field value.

<?php

/**
* Log in to Google account and go to account page
*
*/

$USERNAME = 'youraccount@gmail.com';
$PASSWORD = 'password';
$COOKIEFILE = 'cookies.txt';

// initialize curl handle used for all requests
$ch = curl_init();

// set some options on the handle
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);

// url of our first request fetches the account login page
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);

// extract form fields from account login page
$formFields = getFormFields($data);

// inject email and password into form
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);

$post_string = http_build_query($formFields); // build urlencoded POST string for login

// set url to login page as a POST request
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);

// execute login request
$result = curl_exec($ch);

// check for "Redirecting" message in title to indicate success
// based on your language - you may need to change this to match some other string
if (strpos($result, '<title>Redirecting') === false) {
die("Login failed");
var_dump($result);
}

// login likely succeeded - request account page; unset POST so we do a regular GET
curl_setopt($ch, CURLOPT_URL, 'https://myaccount.google.com/?utm_source=OGB');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);

// execute request for login page using our cookies
$result = curl_exec($ch);

echo $result;


// helpef functions below

// find google "#gaia_loginform" for logging in
function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

// extract all <input fields from a form
function getInputs($form)
{
$inputs = array();

$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);

if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);

if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';

if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

PHP using CURL: is there a way to emulate a cookie instead of saving it to a file?

Cookies are simple text headers sent along with the request. CURL allows you to specify those directly using CURLOPT_COOKIE.

curl_setopt($ch, CURLOPT_COOKIE, 'key=value;anotherkey=anothervalue');

If you know what information to send, you can construct your own cookie header this way. The COOKIEJAR/COOKIEFILE options just automate parsing, saving and sending. You'll have to do that manually (read received Cookie headers, create Cookie headers to be send), if you don't want to write to a file.

how to handle curl session and cookies in php

You can modify

dirname(__FILE__) . "/cookies.txt"

Into something like

dirname(__FILE__) . '/user_cookies/' . $username . '.txt'

You will need to sanitize username for that line so that it will not contain any invalid characters.

Also, set /user_cookies/ permissions to something like 777.

This way you won't need to check if user has cookies or not. If not, the file will be created. If user has them, existing file content will be used.

You could also store cookies in database, but that's way more complicated.

Using cURL to read, completing some steps, then posting

The token is probably no longer good because it is associated with a session cookie that gets set when you access the site. Since file_get_contents has no cookie tracking, you should use cURL to request the initial URL, grab the token, do your calculations, and then post back using cURL again.

To get cURL to keep track of the cookies, use the CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR options for the cURL handle.

$cookies = '/tmp/cookies.txt';  // path to cookie file
$ch = curl_init('http://site.com');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
//...
$res = curl_exec($ch);

// grab token here...

// do calculations here...

curl_setopt($ch, CURLOPT_URL, 'http://site.com/next-url');

$res = curl_exec($ch); // execute next request on same handle

Here are some other answers of mine that use cURL to login to various websites and perform actions; looking at the code may be of help to you.

  • Login to Google with PHP and Curl, Cookie turned off?
  • PHP Curl - Cookies problem
  • Trouble getting a list of cities from LS
  • How to login in with Curl and SSL and cookies
  • How to make Curl post Using Php involving cookies
  • Retrieve Android Market mylibrary with curl
  • php cURL log into jsp website and return HTML

Login with curl and move to another page

If you want to go to /buy after you log in, just use the same curl handle and issue another request for that page. cURL will retain the cookies for the duration of the handle (and on subsequent requests since you are saving them to a file and reading them back with the cookie jar.

For example:



$user_agent       = "Mozilla/5.0 (X11; Linux i686; rv:24.0) Gecko/20140319 Firefox/24.0 Iceweasel/24.4.0";
$curl_crack = curl_init();

CURL_SETOPT($curl_crack,CURLOPT_URL,"https://www.vininspect.com/en/account/login");
CURL_SETOPT($curl_crack,CURLOPT_USERAGENT,$user_agent);
CURL_SETOPT($curl_crack,CURLOPT_PROXY,"183.78.169.60:37899");
CURL_SETOPT($curl_crack,CURLOPT_PROXYTYPE,CURLPROXY_SOCKS5);
CURL_SETOPT($curl_crack,CURLOPT_POST,True);
CURL_SETOPT($curl_crack,CURLOPT_POSTFIELDS,"LoginForm[email]=naceriwalid%40hotmail.com&LoginForm[password]=passwordhere&toploginform[rememberme]=0&yt1=&toploginform[rememberme]=0");
CURL_SETOPT($curl_crack,CURLOPT_RETURNTRANSFER,True);
CURL_SETOPT($curl_crack,CURLOPT_FOLLOWLOCATION,True);
CURL_SETOPT($curl_crack,CURLOPT_COOKIEFILE,"cookie.txt"); //Put the full path of the cookie file if you want it to write on it
CURL_SETOPT($curl_crack,CURLOPT_COOKIEJAR,"cookie.txt"); //Put the full path of the cookie file if you want it to write on it
CURL_SETOPT($curl_crack,CURLOPT_CONNECTTIMEOUT,30);
CURL_SETOPT($curl_crack,CURLOPT_TIMEOUT,30);

$exec = curl_exec($curl_crack);
if(preg_match("/^you are logged|logout|successfully logged$/i",$exec))
{
$post = array('search' => 'keyword', 'abc' => 'xyz');

curl_setopt($curl_crack, CURLOPT_POST, 1); // change back to GET
curl_setopt($curl_crack, CURLOPT_POSTFIELDS, http_build_query($post)); // set post data
curl_setopt($curl_crack, CURLOPT_URL, 'http://example.com/buy'); // set url for next request

$exec = curl_exec($curl_crack); // make request to buy on the same handle with the current login session
}

Here are some other examples of using PHP & cURL to make multiple requests:

How to login in with Curl and SSL and cookies (links to multiple other examples)

Grabbing data from a website with cURL after logging in?

Pinterest login with PHP and cURL not working

Login to Google with PHP and Curl, Cookie turned off?

PHP Curl - Cookies problem



Related Topics



Leave a reply



Submit