Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CURL and PHP to get facebook cookie when login

I'm trying to get my_cookie.txt with the facebook cookie so I can re-use it with CURL for other facebook pages.

Here is my PHP code... When I try this... i see the facebook login page but it gives me an error saying my cookies in my browser must be enable... BUT they are enable.

$email = 'my email';
$password = 'mypassword';
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php');
    curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($email).'&pass='.urlencode($password));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
$page =      curl_exec($ch);

echo $page;

Here is the error I see

enter image description here

Any idea what I'm doing wrong?

like image 783
user3011784 Avatar asked Jan 11 '15 21:01

user3011784


2 Answers

First of all it is against the TOS of facebook (better use api).

The login is just not about to hitting the login page. You have to browse the home page first (using curl in this case) and store the cookie in jar. Then during the login use the cookie with your login request. You may need to find the token or something like that from the home page (if they use any).

So the steps are for any site you want to make a login request:

1) Browse home page using curl. Store cookies using jar. And don't forget to close the curl.

2) If the page has any token or hidden parameter then parse that from the html.

3) Initialize a new curl, prepare post parameter with user/pass + hidden parameters. Don't forget to add cookie jar.

like image 93
Sabuj Hassan Avatar answered Nov 16 '22 09:11

Sabuj Hassan


try adding these lines:

curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
curl_setopt( $ch, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $ch, CURLOPT_COOKIEFILE, uniquefilename );

From: PHP Curl And Cookies

like image 1
manuelbcd Avatar answered Nov 16 '22 08:11

manuelbcd