Log in Register

Log in

Facebook Remote Status Update with PHP/cURL Bot

Facebook login form

** The script in this post no longer working properly. I have updated the script and posted at New and Updated! Facebook Remote Status Update with PHP/cURL Bot  **

 

In previous posts, the discussion is mainly focus on getting web page source file and perform scraping to the text file. In this post, I will show you how I use PHP/cURL to login into Facebook account and post status update at Facebook wall. Once we know how to remote posting using PHP/cURL, we can do many things such as auto posting comment into forum or blog, fill up contact form and send email to our target, login to website and pull out information we need.

For this test case, I am using XAMPP in the PC and login to Facebook mobile interface which is much simpler than its desktop version. You can try to compare Facebook login source file for both desktop and mobile version.

From the browser, go to http://m.facebook.com and there is only one login form.

Facebook login form

View the source file from Facebook http://m.facebook.com and you can find the login form like this:

<form method="post" class="mobile-login-form _5spm" id="login_form" novalidate="1" action="https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&amp;refid=8"><input type="hidden" name="lsd" value="AVoWv8Td" autocomplete="off" /><input type="hidden" name="charset_test" value="€,´,€,´,?,?,?" /><input type="hidden" name="version" value="1" /><input type="hidden" id="ajax" name="ajax" value="0" /><input type="hidden" id="width" name="width" value="0" /><input type="hidden" id="pxr" name="pxr" value="0" /><input type="hidden" id="gps" name="gps" value="0" /><input type="hidden" autocomplete="off" name="m_ts" value="1391231421" /><input type="hidden" autocomplete="off" name="li" value="vYHsUnvLbcJp7jvZLQLAYtHp" /><input type="hidden" autocomplete="off" name="signup_layout" value="layout|lower_subdued_button||s_btn|special||l_btn|confirm||signupinstr||logininstr||st|create||launched_Jan9" /><div class="_56be _5sob"><div class="_55wo _55x2 _56bf"><input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email or Phone" type="text" /><input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" placeholder="Password" name="pass" type="password" /><div class="_55ws"><button type="submit" value="Log In" class="touchable _56bs _56b_ _56bw _56bu" name="login" data-sigil="touchable"><span class="_55sr">Log In</span></button></div></div></div><div class="_52jj _5t3b"><a class="touchable _56bs _5t3b _56bw _56bv" href="/r.php?refid=8" role="button" data-sigil="touchable"><span class="_55sr">Create New Account</span></a></div><noscript><input type="hidden" autocomplete="off" name="_fb_noscript" value="true" /></noscript></form>

 

We need to get the login URL and form fields for posting using PHP/cURL. The important information we need looks like this after some arrangement:

<form method="post" class="mobile-login-form _5spm" id="login_form" novalidate="1" action="https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fm.facebook.com%2F&amp;refid=8">

<input type="hidden" name="lsd" value="AVoWv8Td" autocomplete="off" />
<input type="hidden" name="charset_test" value="€,´,€,´,?,?,?" />
<input type="hidden" name="version" value="1" />
<input type="hidden" id="ajax" name="ajax" value="0" />
<input type="hidden" id="width" name="width" value="0" />
<input type="hidden" id="pxr" name="pxr" value="0" />
<input type="hidden" id="gps" name="gps" value="0" />
<input type="hidden" autocomplete="off" name="m_ts" value="1391231421" />
<input type="hidden" autocomplete="off" name="li" value="vYHsUnvLbcJp7jvZLQLAYtHp" />
<input type="hidden" autocomplete="off" name="signup_layout" value="layout|lower_subdued_button||s_btn|special||l_btn|confirm||signupinstr||logininstr||st|create||launched_Jan9" />
<input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email or Phone" type="text" />
<input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" placeholder="Password" name="pass" type="password" />
<input type="hidden" autocomplete="off" name="_fb_noscript" value="true" />
</form>

 

We need to extract out URL from "action" field, as well as "name" and value". We should ignore other HTML tags.

File fbform.php

<?php
define('FB','https://m.facebook.com');
define('FORM','~<form method="post" (.*?)</form>~s');
define('ACTION','~action=(?:["\'])?([^"\'\s]*)~i');
define('INPUT','~<input(.*?)>~');
define('NAME','~name=(?:["\'])?([^"\'\s]*)~i');
define('VALUE','~value=(?:["\'])?([^"\'\s]*)~i');

class FBform extends HttpCurl	{
private $_url;
private $_inputs = array();

public function __construct() 	{}	 	
public function __destruct()	{}
	
public function fbLogin($username, $password) {
	unset ($this->_inputs);
	unset ($this->_url);	
	$this->getFormFields();
	$this->_inputs['email']=$username;
	$this->_inputs['pass']=$password;
	$post_field = $this->arrayImplode( '=', '&', $this->_inputs);
	$this->post($this->_url,  $post_field);
}
	
public function fbStatusUpdate($status) {
	unset ($this->_inputs);
	unset ($this->_url);	
	$this->getFormFields();
	$this->_inputs['status']=$status;
	$this->_url = FB . $this->_url;
	$post_field = $this->arrayImplode( '=', '&', $this->_inputs);
	$this->post($this->_url,  $post_field);
}
	
public function arrayImplode( $glue, $separator, $array ) {
	$string = array();
	foreach ( $array as $key => $val ) {
		if ( is_array( $val ) )
		$val = implode( ',', $val );
		$string[] = "{$key}{$glue}{$val}";
	}
	return implode( $separator, $string );
}

public function getFormFields() {
	if (preg_match(FORM, parent::getBody(), $form)) {
		preg_match(ACTION, $form[0], $action); 
		$this->_url= $action[1];
		preg_match_all(INPUT, $form[0], $fields); 	
		
		foreach ($fields[0] as $field) {
			if (preg_match(NAME, $field, $name)) {
				$name = $name[1];
                $value = '';

			if (preg_match(VALUE, $field, $value))	$value = $value[1];

			if ($value!=NULL) 	 $this->_inputs[$name] = $value;			
			}
		}		
		return $this->_inputs;	
		} else {
		echo "Error, Form not found!";  }
	}		
}

?>

 

The function getFormFields() will return extracted form URL and fields. Sample output of getFormFields:

Array
(
    [fb_dtsg] => AQDUz9bF
    [charset_test] => €,´,€,´,水,Д,Є
    [update] => Share
    [privacy] => {"row_created_time":1391497489,"row_updated_time":1390724300,"value":80,"owner":100007586291391,"_pmc_":1391497489,"friends":0,"lists_anon":[],"ids_anon":[],"lists_x_anon":[],"ids_x_anon":[],"tdata":[],"lists":[],"lists_x":[],"objects":[],"no_tag_expansion":0}
)

 

To get source file from Facebook, login and post status, we need to keep track of cookie file from Facebook.

File httpcurl.php

<?php
 
 // Class HttpCurl
class HttpCurl {
    private $_ch, $_cookie, $_info, $_body, $_error;
      
    public function __construct() {
        if (!function_exists('curl_init')) {
            throw new Exception('cURL not enabled!');
        } 
    }
  
    public function get($url) {
        $this->_ch = curl_init();
	curl_setopt($this->_ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0');
	curl_setopt($this->_ch, CURLOPT_POST, 0);		
        curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($this->_ch, CURLOPT_MAXREDIRS, 5);   
        curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($this->_ch, CURLOPT_COOKIEFILE, getcwd () . '/facebook_cookie' );
        curl_setopt($this->_ch, CURLOPT_COOKIEJAR, getcwd () . '/facebook_cookie' );	
	curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt($this->_ch, CURLOPT_SSL_VERIFYHOST, false );		
        curl_setopt($this->_ch, CURLOPT_URL, $url);
        $this->_body = curl_exec($this->_ch);
        $this->_info  = curl_getinfo($this->_ch);
        $this->_error = curl_error($this->_ch);
        curl_close($this->_ch);    		
    }
	
    public function post($url,  $post_data) {
        $this->_ch = curl_init();
	curl_setopt($this->_ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0');	
        curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($this->_ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($this->_ch, CURLOPT_HEADER, 0);	
        curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt($this->_ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($this->_ch, CURLOPT_ENCODING, "" );	
	curl_setopt($this->_ch, CURLOPT_POST, TRUE);
	curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($this->_ch, CURLOPT_COOKIEFILE, getcwd () . '/facebook_cookie' );
        curl_setopt($this->_ch, CURLOPT_COOKIEJAR, getcwd () . '/facebook_cookie' );		
        curl_setopt($this->_ch, CURLOPT_URL, $url);
        $this->_body = curl_exec($this->_ch);
        $this->_info  = curl_getinfo($this->_ch);
        $this->_error = curl_error($this->_ch);
	curl_close($this->_ch);  		
    }	
  
	// Get http_code
    public function getStatus() {
        return $this->_info[http_code];
    }
      
	// Get web page header information
    public function getHeader() {
        return $this->_info;
    }
     public function getHandle() {
        return $this->_ch;
    } 
	// Get web page content
    public function getBody() {
        return $this->_body;
    }
      
    public function __destruct() {
    } 		
	
}
  
?>

 

The cookie file will be store in the same directory with our script. You can file cookie in text file format named "facebook_cookie.txt".

To run the script, execute fbautopost.php.

<?php
include 'httpcurl.php';
include 'fbform.php';

$fbhomepage = 'http://m.facebook.com';
$username = "xxxxxxxx";   // Insert your Facebook login email
$password = "xxxxxxx";    //Insert your Facebook password
$status = "This is my script on remote status update with php/cURL on Facebook! Check it out at http://php8legs.com! ";

$pages = new FBform();
$pages->get($fbhomepage);  
$pages->fblogin($username, $password);
$pages->get($fbhomepage);
$pages->fbstatusupdate($status);
?>

 

First, we request for Facebook mobile main page http://m.facebook.com and will be redirected to https://m.facebook.com/?_rdr. We set cURL options to 

        curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($this->_ch, CURLOPT_MAXREDIRS, 5);  

 

Then we call $pages->fblogin($username, $password) to login Facebook with cURL.

 

Facebook auto login

 

After successful login, we have two forms, one is Status Update box and another Search box. Look for Status Update form from the source file,

<form method="post" class="composer_form" id="composer_form" action="/a/home.php?refid=8"><input type="hidden" name="fb_dtsg" value="AQArDqOT" autocomplete="off" /><input type="hidden" name="charset_test" value="€,´,€,´,水,Д,Є" /><table cellspacing="0" cellpadding="0" class="comboInput"><tr><td class="inputPic"><a href="/chinhock.tan.35?refid=8"><img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc1/t1/c14.0.47.47/s40x40/252231_1002029915278_1941483569_t.jpg" width="40" class="profpic img" alt="Chin Hock Tan" /></a></td><td class="inputCell"><textarea class="input composerInput composerInputSmall composerInputWithPic" id="composerInput" name="status" rows="2" cols="15" data-sigil="textarea"></textarea></td><td class="btnCell"><input value="Share" type="submit" name="update" class="_56bs _5of- _56bu" data-sigil="composer-submit" /></td></tr></table><input type="hidden" name="target" /><span class="mfss fcg"><span>Posting to:&nbsp;<a href="/privacy/selector/?redir=%2Fcomposer%2F%3Fsbu%3D%252Fa%252Fhome.php%26fin%3Dstatus%26hash%3DAZsI791q6XyciNux&amp;gfid=AQCrhPbFnPplNYXS&amp;refid=8"><span><img src="https://fbstatic-a.akamaihd.net/rsrc.php/v2/yp/r/--soLpMIbaJ.png" width="10" height="11" class="advancedComposerPrivacyLinkIcon img" />&nbsp;<span class="fcg">Public</span></span></a><input type="hidden" autocomplete="off" name="privacy" value="&#123;&quot;row_created_time&quot;:1391310926,&quot;row_updated_time&quot;:1390724300,&quot;value&quot;:80,&quot;owner&quot;:100007586291391,&quot;_pmc_&quot;:1391310926,&quot;friends&quot;:0,&quot;lists_anon&quot;:[],&quot;ids_anon&quot;:[],&quot;lists_x_anon&quot;:[],&quot;ids_x_anon&quot;:[],&quot;tdata&quot;:[],&quot;lists&quot;:[],&quot;lists_x&quot;:[],&quot;objects&quot;:[],&quot;no_tag_expansion&quot;:0&#125;" /></span><span role="separator" aria-hidden="true"> · </span><a href="/composer/?sbu=%2Fa%2Fhome.php&amp;fin=status&amp;hash=AZsI791q6XyciNux&amp;refid=8">More Options</a></span></form>

 

 Remove unwanted HTML tags and here are tags that we need to extract:

<form method="post" class="composer_form" id="composer_form" action="/a/home.php?refid=8">
<input type="hidden" name="fb_dtsg" value="AQArDqOT" autocomplete="off" />
<input type="hidden" name="charset_test" value="€,´,€,´,水,Д,Є" />
<input value="Share" type="submit" name="update" class="_56bs _5of- _56bu" data-sigil="composer-submit" />
<input type="hidden" name="target" />
<input type="hidden" autocomplete="off" name="privacy" value="&#123;&quot;row_created_time&quot;:1391310926,&quot;row_updated_time&quot;:1390724300,&quot;value&quot;:80,&quot;owner&quot;:100007586291391,&quot;_pmc_&quot;:1391310926,&quot;friends&quot;:0,&quot;lists_anon&quot;:[],&quot;ids_anon&quot;:[],&quot;lists_x_anon&quot;:[],&quot;ids_x_anon&quot;:[],&quot;tdata&quot;:[],&quot;lists&quot;:[],&quot;lists_x&quot;:[],&quot;objects&quot;:[],&quot;no_tag_expansion&quot;:0&#125;" />
</form>

 

To update status to Facebook wall, call function $pages->fbstatusupdate($status). You can change $status to message you want to update. In fact, you can also scrape information from other websites and assign to $status.

 

Facebook auto update with cURL

My Facebook friends will see output like this:

Facebook auto update with cURL

 

Happy trying!!

Last modified on Thursday, 03 November 2016 06:15
Rate this item
(7 votes)

28 comments

  • Agus

    Hi, I try your code. I run fbautopost.php my fb are log on and I get facebook_cookie. But, the page is blank no facebook update form. How about it?

    posted by Agus Thursday, 16 October 2014 17:02 Comment Link
  • Chin-Hock Tan

    Hello,
    This post was written in Feb 2014. Facebook has changed the mobile input form.
    I ran a test and here are 4 lines changes to fbform.php so that facebook autoposting can work.
    At the top, change these definition:
    define('NAME','~name="(.*?)"~i');
    define('VALUE','~value="(.*?)"~i');
    define('ACTION','~action="(.*?)"~i');

    In the public function fbStatusUpdate($status), change
    $this->_inputs['status']=$status;
    to
    $this->_inputs['xc_message']=$status;

    You should be able to autopost with the above changes. Good luck!

    posted by Chin-Hock Tan Friday, 17 October 2014 03:29 Comment Link
  • agus

    Thanks sir it's work now, but how I can get access token and save to existing folder ?

    posted by agus Friday, 17 October 2014 14:50 Comment Link
  • Chin-Hock Tan

    If you want to store user access token, better use Facebook SDK. There are some good tutorials that you can find. You can check out http://thinkdiff.net/ for example.

    posted by Chin-Hock Tan Saturday, 18 October 2014 02:16 Comment Link
  • Franky Yodi

    exscuse me mr chin hock tan
    i tried what u suggest before
    but here is it the result

    http://i.imgur.com/4BTJNNe.png

    posted by Franky Yodi Monday, 27 October 2014 03:14 Comment Link
  • Chin-Hock Tan

    Hello Franky,
    If you are using XAMPP for script development, under Windows environment, you can just go to C:\xampp\php\php.ini and turn off safe_mode as well as disable open_basedir like below.
    safe_mode=Off
    ;open_basedir =

    If you are on a live server, then you might want to apply solution as mentioned in
    http://slopjong.de/2012/03/31/curl-follow-locations-with-safe_mode-enabled-or-open_basedir-set/

    posted by Chin-Hock Tan Monday, 27 October 2014 07:14 Comment Link
  • Kamze

    When I login using curl, my facebook is locked. Because I login from different place. That mean, facebook detect an IP Server. How the way to hidden local ip from curl request ?

    posted by Kamze Wednesday, 29 October 2014 18:21 Comment Link
  • Chin-Hock Tan

    Hello Kamze,
    Yes, I was in Malaysia and try to login account of a Taiwanese client to set up Facebook apps and immediately blocked by Facebbok. Guest Facebook detected switching of country IP in such a short time.

    It can be difficult as PHP/cURL can not help you hide your IP. If you are creating an apps which require Facebook login for users in various location, better use Facebook SDK.

    posted by Chin-Hock Tan Thursday, 30 October 2014 00:22 Comment Link
  • Franky Yodi

    for kamze up there...
    if about login from different place
    i got some Solutions hehe...
    1st make sure your webserver is in came with your country too...
    2nd make sure you logged on ur account from pc
    3rd set this http://i.imgur.com/sUfGKgs.png
    4th execute the script...
    5td tada, push screen popup appear...
    (then save browser as known)

    While i tried step 1 from singapore
    (account always logged out and forcing me change passwd..
    even i alrdy set that was me log in)

    for mr chin hock tan, can you help me fixing some scripts?
    login was success
    but posting to page / groups failure from database...

    posted by Franky Yodi Thursday, 30 October 2014 08:55 Comment Link
  • Chin-Hock Tan

    Hello Franky,
    What are the scripts? My scripts or yours?

    posted by Chin-Hock Tan Thursday, 30 October 2014 09:14 Comment Link
  • Franky Yodi

    its wasnt my script heheh
    about autopost Dhammapada with cron
    back then its still working even safe mode enabled
    then...
    at august 14 the script suddenly dead...
    i guess some variable changed bt i dnt knw how to fix it..

    and how can i send the scripts?

    posted by Franky Yodi Thursday, 30 October 2014 09:32 Comment Link
  • Franky Yodi

    email sent :D

    posted by Franky Yodi Thursday, 30 October 2014 10:27 Comment Link
  • Chin-Hock Tan

    Hello Franky,
    I checked the parsing of facebook login form in the "login" function. Facebook has changed the form format. Your script not able to login to facebook. You might want to change to my sample script with changes mentioned in the earlier comments.

    posted by Chin-Hock Tan Thursday, 30 October 2014 22:47 Comment Link
  • Ahmet

    Sorry my english bad. I try your code but ;
    "Undefined property: FBform::$_url in C:\wamp\www\fbform.php on line 24"
    and
    "Undefined property: FBform::$_url in C:\wamp\www\fbform.php on line 32"
    not workink please help me ?

    posted by Ahmet Saturday, 20 December 2014 14:06 Comment Link
  • Chin-Hock Tan

    Hello Ahmet, what is the version of your PHP?

    posted by Chin-Hock Tan Sunday, 21 December 2014 09:52 Comment Link
  • Xavier Barroso

    HI Mr Tan,

    Thank you for the code it works well, however if I want to post on one of my fan pages and not my profile wall how do I do that?

    I tried this:

    define('FB','https://m.facebook.com/login.php?next=https://m.facebook.com/websitehostingservicesgoldcoast&refsrc=https://m.facebook.com/websitehostingservicesgoldcoast&refid=17');

    AND

    $fbhomepage = 'https://m.facebook.com/login.php?next=https://m.facebook.com/websitehostingservicesgoldcoast&refsrc=https://m.facebook.com/websitehostingservicesgoldcoast&refid=17';

    but no luck

    it you have any ideas would be nice to hear it.

    cheers Xavier

    posted by Xavier Barroso Sunday, 25 January 2015 01:49 Comment Link
  • Chin-Hock Tan

    Hello Xavier,
    To post for facebook page, you can use facebook API.
    You can perform the setup form my facebook article
    How to auto publish post on Facebook Fan Page as admin using Facebook PHP SDK V4 Graph API v2.2 (1) (2) and (3).

    You can then customize your own query at (4) for auto update. No need approval from Facebook team if you are the only person update the page.

    My page works well so far with the API. Update product every 4 hours.
    https://www.facebook.com/pages/Wagga-Shop/207278019334554

    posted by Chin-Hock Tan Sunday, 25 January 2015 02:17 Comment Link
  • bambanggr

    any tutorial for using php sdk?
    also i try this code just got blank page and facebook_cookie
    i try on localhost.

    posted by bambanggr Friday, 30 January 2015 08:10 Comment Link
  • Chin-Hock Tan

    Hello Bambanggr,
    I don't have tutorial on using PHP SDK.
    For this code, you can run under local host. However, facebook constantly change the tag of login form. This article was written a year ago. So you might want to check any changes to facebook login form.

    posted by Chin-Hock Tan Friday, 30 January 2015 08:45 Comment Link
  • egon

    can you update the script?! ive tride the code but it doesnt work, just a blank page without errors and nothing happens...

    posted by egon Tuesday, 17 March 2015 20:49 Comment Link
  • egon

    can you update the script?! ive tride the code but it doesnt work, just a blank page without errors and nothing happens...

    posted by egon Tuesday, 17 March 2015 20:49 Comment Link
  • Chin-Hock Tan

    Hello Egon,
    That was because facebook change the HTML tags again. You need to find the new tags and change accordingly.
    Scraping facebook in this way is for temporary and ad hoc solution. It could not maintain in long run.

    posted by Chin-Hock Tan Wednesday, 18 March 2015 13:21 Comment Link
  • Domenico Pennacchio

    hi,

    with new version work, i can i publish on my fan page?

    posted by Domenico Pennacchio Tuesday, 02 June 2015 19:23 Comment Link
  • Chin-Hock Tan

    Hello Domenico,
    1) You have to modify my sample script in this article to scrape facebook login.
    2) This code is for remote update facebook page. I have not tried on Fan Page.

    posted by Chin-Hock Tan Wednesday, 03 June 2015 20:55 Comment Link
  • Patrick Famorca

    Hi there, I'd be willing to pay if you updated this for me and only me. Can you email me?

    posted by Patrick Famorca Saturday, 29 August 2015 08:57 Comment Link
  • Chin-Hock Tan

    Hello Patrick,
    I have updated and uploaded the new code. Please go to
    http://php8legs.com/en/facebook/45-new-and-updated-facebook-remote-status-update-with-php-curl-bot

    Good luck!

    posted by Chin-Hock Tan Wednesday, 02 September 2015 03:14 Comment Link
  • ata

    thanks a lot dear

    posted by ata Tuesday, 20 October 2015 16:30 Comment Link
  • Alexandre

    How to post an image?

    posted by Alexandre Tuesday, 19 April 2016 00:23 Comment Link

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.



Anti-spam: complete the task
back to top