1

For my project purpose, i need to login to my facebook account remotely and retrieve some information from there. For the login purpose, i am using cURL library of PHP. On execution of the code, facebook page asks me to enable the cookies on my browser which i have already enabled. Is there any problem with the code? Can anybody help me out in logging into my account remotely? I am a newbie and would really appreciate if any help comes. Here is the code

<?php

 //create array of data to be posted

 $post_data['email'] = '*********';

 $post_data['password'] = '**********';

 $post_data['action'] = 'login';


 //traverse array and prepare data for posting 

 foreach ( $post_data as $key => $value) {

  $post_items[] = $key . '=' . $value;

 }

 //create the final string to be posted using implode()

 $post_string = implode ('&', $post_items);



 //create cURL connection

 $ch = curl_init('https://login.facebook.com/login.php?');



 //set options

 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

 curl_setopt($ch, CURLOPT_USERAGENT, 
   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);



 //set data to be posted

 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);



 //perform our request

 $result = curl_exec($ch);



 print_r($result);



 //close the connection

 curl_close($ch);

 ?>

insightful
  • 189
  • 1
  • 5
  • 14

1 Answers1

4

To use cookies with curl you'll need to specify a "cookie jar", which is where the cookies should be stored and loaded from. You can do this using the CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR options. Something like this should do it:

curl_setopt($ch, CURLOPT_COOKIEJAR, 'facebook_cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'facebook_cookies.txt');

Check out http://php.net/curl_setopt for more information.

As an aside, you can also pass $post_fields as an array to CURLOPT_POSTFIELDS, so you don't actually have to generate the query string yourself. If you want to do that, there is also a http_build_query() function that does this. This is unrelated to the issue you posted though.

Daniel Egeberg
  • 8,359
  • 31
  • 44