I almost have this code complete, but I have hit a snag, I am writing an autopin script to pinterest and it loads the page but wont submit :( I just need a little help to complete this script.
function login() {
// Create Cookie File
$cookiefile = './pinitcookie.txt';
if (file_exists($cookiefile)) { unlink ($cookiefile); }
//User and pass to Pinterest
$email = '<email>';
$password = '<passowrd>';
// initial login page which redirects to correct sign in page, sets some cookies
$URL = 'https://pinterest.com/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//Create the page for login
$page = curl_exec($ch);
preg_match('/^Set-Cookie:\s*([^;]*)/mi', $page, $m);
//Get Pinterest CSRF token
parse_str($m[1], $cookies);
$token=$cookies['csrftoken'];
// try to find the actual login form
if (!preg_match('/<form id="AuthForm".*?<\/form>/is', $page, $form)) {
die('Failed to find log in form!');
}
$form = $form[0];
// find the action of the login form
if (!preg_match('/action="([^"]+)"/i', $form, $action)) {
die('Failed to find login form url');
}
$URL2 = "https://pinterest.com".$action[1]; // this is our new post url
// find all hidden fields which we need to send with our login, this includes security tokens
$count = preg_match_all('/<input type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"/i', $form, $hiddenFields);
$postFields = array();
// turn the hidden fields into an array
for ($i = 0; $i < $count; ++$i) {
$postFields[$hiddenFields[1][$i]] = $hiddenFields[2][$i];
}
// add our login values
$postFields['email'] = $email;
$postFields['csrfmiddlewaretoken'] = $token;
$postFields['password'] = $password;
$post = '';
// convert to string, this won't work as an array, form will not accept multipart/form-data, only application/x-www-form-urlencoded
foreach($postFields as $key => $value) {
$post .= $key . '=' . urlencode($value) . '&';
}
$post = substr($post, 0, -1);
curl_setopt($ch, CURLOPT_URL, $URL2);
curl_setopt($ch, CURLOPT_REFERER, $URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$page = curl_exec($ch); // make request
if ($page === FALSE) {
var_dump(curl_getinfo($ch));
}
post_to_pinterest($ch, $token, $cookiefile, $URL);
}
function post_to_pinterest($ch, $token, $cookiefile, $URL) {
#URL3 = "http://www.pinterest.com/pin/create/button/?url=" . rawurlencode(get_permalink($post)) . "&media=" . rawurlencode($url) . "&description=" . rawurlencode(get_the_title($post));
#$URL3 = "http://www.pinterest.com/pin/create/button/?url=http://www.biofects.com&media=http://www.biofects.com/wp-content/uploads/2013/01/Untitled-11.png&description=This is a test";
$URL3 = "http://pinterest.com/pin/create/button/?";
#echo $URL3;
$posting = "board=test&url=http://www.domain.com&media=http://www.domain.com/wp-content/uploads/2013/01/Untitled-11.png&description=This is a test&csrfmiddlewaretoken=$token";
$x="error";
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($ch, CURLOPT_URL, $URL3);
//curl_setopt($ch, CURLOPT_REFERER, $URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $posting);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_VERBOSE, true);
$pagetopost = curl_exec($ch);// make request
if($x != 'error' & trim($x) != ''){
echo "Curl Try Error".$x;
}
// preg_match('/^Set-Cookie:\s*([^;]*)/mi', $pagetopost, $m);
//Get Pinterest CSRF token
// parse_str($m[1], $cookies);
// $token=$cookies['csrftoken'];
curl_close($ch);
}
login();
any help to make this happen would be awesome, Thanks
BTW I see people have this done but are selling this code, when complete I will post it FREE :)
Hey everyone I have published the wordpress plugin. I ave tested it and it has worked on 3 domain, if you dont use wordpress you can take the code and make it your own. you can find the plugin here http://wordpress.org/extend/plugins/lazy-pinner/
Related
I am trying to make a login php post but its not posting correctly... i need the following sent to the Curl but its just not sending
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'j_username='.$username.'&j_password='.$password.'&tk_trp ='.$tk_trp);
Is what i am currently trying to use and its just not taking is there something anyone notices that i am doing wrong? Any advice would be great thanks!
I have been stuck on this a good while now and its just not coming together for me so thought i would reach out :)
<?php
$token = GetStringBetween(getURL("tokenlocatonurl"),"start'", "'");
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
$username = 'myuser';
$password = 'mypass';
$tk_trp = '$token';
$loginUrl = 'lognurlhere';
function getURL($u){
$u = file_get_contents("http://{$u}");
return $u != false ? $u : "";
}
function GetStringBetween($string, $start, $finish){
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters curl_setopt($ch, CURLOPT_POSTFIELDS, 'j_username='.$username'&j_password='.$password'&tk_trp='.$tk_trp');
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
//the login is now done and you can continue to get the
//protected content.
//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'url to grab content from');
//execute the request
$content = curl_exec($ch);
?>
Problems I see with your code are:
You should use http_build_query to encode your data.
You should enable CURLOPT_COOKIESESSION.
You should disable CURLOPT_POST AFTER you logged in.
It's better to use a user agent because some sites block suspicious user agents.
Use both CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR and use '-' to store it in memory.
Here is final code:
<?php
$data = [
'j_username' => $username,
'j_password' => $password,
'tk_trp' => $tk_trp
];
$ch = curl_init("http://example.com/login");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, '-');
curl_setopt($ch, CURLOPT_COOKIEJAR, '-');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "http://example.com/dashboard");
curl_setopt($ch, CURLOPT_POST, 0);
$x = curl_exec($ch);
echo $x;
Could it be that extra space in &tk_trp and = ?
curl_setopt($ch, CURLOPT_POSTFIELDS, 'j_username='.$username.'&j_password='.$password.'&tk_trp ='.$tk_trp);
I been trying to log into barnesandnoble.com mobile site with curl
and have had no luck so far. I get back the page with no errors
and it defaults my email into the email input form box of the login page again (in the form returned from print $result).
The same code can actually let me go into ebay correctly
by changing the LOGINURL to point to ebay's login
The only difference being that barnesandnobles is https://
and ebay login was http://
Also, I believe that barnes website is asp/aspx so I don't know
how that would handle cookies and _state differently
Any help would be appreciated as I been trying to debug this for the
past 16hrs
also, my cookie.txt is writable and working
<?php
$cookie_file_path = "C:/test/cookie.txt";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
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_URL, $LOGINURL);
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);
$content = curl_exec($ch);
curl_close($ch);
unset($ch);
// NAME="path_state" value="6657403">
if(stristr($content,"path_state")){
$array1 = explode('path_state" value="',$content);
$content1 = $array1[1];
$array2 = explode('">',$content1);
$content2 = $array2[0];
}
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$POSTFIELDS = "d_hidPageStamp=V_3_17&hidViewMode=opSignIn&stage=signIn&previousStage=mainStage&path_state=" . $content2 . "&emailAddress=YOUREMAILHERE#gmail.com&acctPassword=YOURPASSWORD";
$reffer = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
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_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec($ch);
print $result;
?>
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
I'm trying to log in to site and then go to one of the pages and retrieve the data. I have a problem with authorization.
Sample code:
$loginUrl = 'https://strona.pl/authorization'; //action from the login form
$loginFields = array('username'=>'mail#mojmail.pl', 'password'=>'haslo'); //login form field names and values
$remotePageUrl = 'https://strona.pl/pdstrona'; //url of the page you want to save
$login = getUrl($loginUrl, 'post', $loginFields); //login to the site
$remotePage = getUrl($remotePageUrl); //get the remote page
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
$buffer = curl_exec($ch);
//jeżeli pojawił się błąd to go wyświetlimy
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $buffer;
print $status;
}
// wyłącza pokazywanie błędów dla funkcji loadHTML
libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom ->strictErrorChecking = FALSE;
$dom->loadHTML($remotePage);
$xpath = new DOMXpath($dom);
As a result of this query I am redirected to the main page (not the sub). What is important, I enter email address into a script in encoded form. Example: email% 40mojmail.pl
edit
Ok - I will add some information . I am a publisher and working with afilo.pl . Daily checking of rates is very tiring, so I wanted to prepare a script that will collect data once a day and informed me of the changes.
Unfortunately I can not retrieve the data.
Sample cookies from my browser :
Set- Cookie: PHPSESSID = jat102p33s0pmfairri1qiih24 ; expires = Thu, 25 -Dec- 2013 9:16:40 p.m. GMT ; path = / ; domain = . Afilo.pl
I modified the code but it still does not work.
loginUrl = 'https://opentrack.afilo.pl/logowanie'; //action from the login form
$loginFields = array('loginemail'=>'.......','loginhaslo'=>'........');
//login form field names and values
$remotePageUrl = 'https://opentrack.afilo.pl/partner/programy-lista'; //url of the page you want to save
$login = getUrl($loginUrl, 'post', $loginFields); //login to the site
$remotePage = getUrl($remotePageUrl); //get the remote page
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
session_start();
$strCookie = session_name() . '=' . $_COOKIE[ session_name() ] . '; path=/; domain=.afilo.pl';
session_write_close();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
curl_setopt( $ch, CURLOPT_COOKIE, $strCookie );
$buffer = curl_exec($ch);
//je¿eli pojawi³ siê b³¹d to go wyœwietlimy
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $buffer;
print $status;
}
This is the answer to my question. This code works well.
// options
$EMAIL = 'login';
$PASSWORD = 'haslo';
$cookie_file_path = "/cookies/cookies.txt";
$LOGINURL = "https://domainname.com/auth";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
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);
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
$fields = array();
$fields['loginemail'] = $EMAIL;
$fields['loginhaslo'] = $PASSWORD;
$POSTFIELDS = http_build_query($fields);
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
$result = curl_exec($ch);
$remotePageUrl = 'https://domainname.com/partner/programy-lista';
curl_setopt($ch, CURLOPT_URL, $remotePageUrl);
$result = curl_exec($ch);
I been trying to log into barnesandnoble.com mobile site with curl
and have had no luck so far. I get back the page with no errors
and it defaults my email into the email input form box of the login page again (in the form returned from print $result).
The same code can actually let me go into ebay correctly
by changing the LOGINURL to point to ebay's login
The only difference being that barnesandnobles is https://
and ebay login was http://
Also, I believe that barnes website is asp/aspx so I don't know
how that would handle cookies and _state differently
Any help would be appreciated as I been trying to debug this for the
past 16hrs
also, my cookie.txt is writable and working
<?php
$cookie_file_path = "C:/test/cookie.txt";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
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_URL, $LOGINURL);
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);
$content = curl_exec($ch);
curl_close($ch);
unset($ch);
// NAME="path_state" value="6657403">
if(stristr($content,"path_state")){
$array1 = explode('path_state" value="',$content);
$content1 = $array1[1];
$array2 = explode('">',$content1);
$content2 = $array2[0];
}
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$POSTFIELDS = "d_hidPageStamp=V_3_17&hidViewMode=opSignIn&stage=signIn&previousStage=mainStage&path_state=" . $content2 . "&emailAddress=YOUREMAILHERE#gmail.com&acctPassword=YOURPASSWORD";
$reffer = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
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_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec($ch);
print $result;
?>
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
I have this code for logging into Google using Simple DOM Parser with curl. I've tried adding in the cookiejar file, but to no avail. I keep getting the message:
Your browser's cookie functionality is turned off. Please turn it on.
Any idea on how to solve this?
Here's my code for reference:
$html = file_get_html('https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
//... some code for getting post data here
$curl_connection = curl_init('https://accounts.google.com/ServiceLoginAuth');
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_connection, CURLOPT_COOKIEJAR, COOKIEJAR);
curl_setopt($curl_connection, CURLOPT_COOKIEFILE, COOKIEJAR);
curl_setopt($curl_connection, CURLOPT_HEADER, true);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($curl_connection, CURLOPT_TIMEOUT, 120);
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($curl_connection);
curl_close($curl_connection);
echo $result;
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;
}