04 February, 2011

Facebook Share using cURL & PHP

I required a php script for facebook share using curl, found some but none of them worked for me. Found one script that was close to working, so i changed and added some codes in it and finally got it working. So following code snippet can be used for facebook share using curl in php.

The following code uses m.facebook.com for using the share feature. It first logs in a valid facebook user, gets the page after logging in, extracts hidden field values and form action used for posting message, then finally shares the message using curl.

$status = 'YOUR MESSAGE HERE';
$login_email = 'YOUR-EMAIL-ADDRESS';
$login_pass = 'YOUR-FACEBOOK-PASS';

//curl to login to facebook
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
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, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20070309 Firefox/");

//get the page after logging in successfully
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($ch);

//get hidden values
$searchStr = "/name=\"post_form_id\" value=\"(.*?)\"/";
preg_match($searchStr, $page, $matches);
$post_form_id = $matches[1];

$searchStr2 = "/name=\"fb_dtsg\" value=\"(.*?)\"/";
preg_match($searchStr2, $page, $matches1);
$fbDtsg = $matches1[1];

$searchStr3 = "/name=\"charset_test\" value=\"(.*?)\"/";
preg_match($searchStr3, $page, $matches2);
$charsetTest = $matches2[1];

//get the posting url
$searchStr4 = "/id=\"composer_form\" action=\"(.*?)\"/";
preg_match($searchStr4, $page, $matches3);
$frmAction = $matches3[1];

//final post url
$postStatUrl = 'http://m.facebook.com'.$frmAction;

//finally post your message
curl_setopt($ch, CURLOPT_URL, $postStatUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS,'charset_test='.$charsetTest.'&fb_dtsg='.$fbDtsg.'&post_form_id='.$post_form_id.'&status='.$status.'&update=Share');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);

And thats it. Share it.

No comments: