Showing posts with label backend. Show all posts
Showing posts with label backend. Show all posts

Wednesday, March 16, 2011

How to checkin to foursquare via backend using PERL and PHP

Checking in to foursquare is more likely the same as posting a shout out, tweet or status in social network like facebook and twitter.

Foursquare follows authentication via OAuth and this post will teach you how to do it via back-end using PERL and PHP.

I assume you already read my post on how to Login to foursquare via back-end in PERL. You should be able to understand it first to proceed with authentication and do the check-in in users behalf.

Just follow the simple steps for your implementation.

1. You must have a Client ID and the Callback URL. If you don't have yet, create one by going to foursquare developers link - http://developer.foursquare.com/

2. To register a new consumer, click the "Manage OAuthConsumers" link or go to OAuth page - https://foursquare.com/oauth/

3. Enter your Application Name, Application Website, and Callback URL. Please take note that your Callback URL will be your Redirect URI.

4. After successful registration, Client ID and Client Secret will be generated.

5. What we need from now is the Client ID and once we have it, we can now start the coding part.

6. First thing we have to do is to login to users account via back-end. Please see post - Login to foursquare via back-end in PERL

7. After successful login, next step is to authenticate your application. To authenticate your app, you should pass a Client ID and your Callback URL that was registered from Consumer Registration.

$client_id = '<your client id>';
$redirect_uri = '<your callback url>';

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=touch&redirect_uri=$redirect_uri", @header);

$form_data = $response->content;
$form_data =~ s/\n//g;

8. If this is the first time you authenticate your app, return page will be asking users permission to "Allow" the application to access account details and transact in users behalf. We can do this in back-end by implementing REGEX to get the NAME parameter of the value="Allow", then passed it on to authentication URL - https://foursquare.com/oauth2/authenticate.

$form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

$form_action = $1;
$form_allow = $3;

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
$form_data = $response->content;

9. After allowing the application, foursquare will redirect the user to redirect URI that we set on step #7. Your callback URL or redirect URI must capture the CODE parameter and exchange it with TOKEN. This can now be done via PHP.

10. Foursquare will pass the CODE parameter via GET method on our Callback URL. Our Callback URL should be able to capture it and use it in exchange of an access token. To get an access token, we should pass the CODE parameter, Client ID, Client Secret, Callback URL, and Grant Type to the access token URL - https://foursquare.com/oauth2/access_token. Client ID, Client Secret, and Callback URL are data from the consumer registration, and the Grant Type should be equal to "authorization_code". Please take note that this is now on PHP.

$client_id = '<your client id>';
$client_secret = '<your client secret>';
$redirect_uri = '<your callback url>';
$grant_type = 'authorization_code';

$code = $_GET['code'];      
$oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

11. As per implementation below, I use the open stream to get the contents and convert it to JSON which will then return an object with an access token.

$url_handler = fopen("$oauthurl", 'r');
$json = json_decode(stream_get_contents($url_handler));
fclose($url_handler);

$token = $json->access_token;

13. Now that you have the Token, we are now ready to do the Foursquare Check-in. Going back to PERL, what we need to do here is to do a POST request to Foursquare API URL - https://api.foursquare.com/v2/checkins/add. venueId will be the place or location you want to check-in, shout is optional if you want your post to have a custom message, broadcast can be of public or private, and lastly the oauth_token which is the access token we get from step #12. Again, this is now in PERL.

$intVenueID = "<the venue id you want to check-in>";
$strShout = "<your shout message>";
$strToken = "<your access token>";

$response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

print $response->content;

That's it!! Hope you were able to follow. In case you don't, you can refer to the scripts below. Good luck and enjoy!!

- Here's the PERL script, it composes of 2 sub functions: check_foursquare_login() and post_foursquare_checkin()


#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://foursquare.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your foursquare username>";
my $strPass = "<your foursquare password>";
my $client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A";
my $redirect_uri = "http://localhost/foursquare/foursquare.php";
my $status = "testing foursquare status";

my $form_data = &check_foursquare_login($strUser, $strPass, $client_id, $redirect_uri);

if ($form_data =~ /^OK\|/)
{
  my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
  &post_foursquare_checkin($intUserID, $strToken, '', $status);

  unlink($cookie_file);
  print "done!";
}
else
{
  $form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

  my $form_action = $1;
  my $form_allow = $3;

  my $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
  $form_data = $response->content;

  if ($form_data =~ /^OK\|/)
  {
    my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
    &post_foursquare_checkin($intUserID, $strToken, '', $status);

    unlink($cookie_file);
    print "done!";
  }
  else
  {
    unlink($cookie_file);
    print "error authentication!";
  }
}

sub check_foursquare_login
{
  my ($strUser, $strPass, $client_id, $redirect_uri) = @_;

  # log-in to foursquare
  my $response = $lwpua->post('https://foursquare.com/mobile/login',
                      ['username' => $strUser,
                       'password' => $strPass], @header);
  $cookie_jar->extract_cookies( $response );
  $cookie_jar->save;

  $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=wap&redirect_uri=$redirect_uri", @header);

  $form_data = $response->content;
  $form_data =~ s/\n//g;

  return $form_data;
}

sub post_foursquare_checkin
{
  my ($strUserID, $strToken, $intVenueID, $strShout) = @_;
  my ($response);

  $response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

  return $response->content;
}



1;


- Here's the PHP script. Save this in your web server and set this as your callback URL in consumer registration.


<?

$client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A"; // hotshots client id
$client_secret = "NEHCL3UL0KS1QJD22NLIQ5RMR4BL4IUZIJZW25VHSJ4JPZKB";
$grant_type = "authorization_code";
$redirect_uri = "http://localhost/foursquare/foursquare.php";

$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

        $url_handler = fopen("$oauthurl", 'r');
        $json = json_decode(stream_get_contents($url_handler));
        fclose($url_handler);

        $token = $json->access_token;
        if ($token) {
                $info_contents = `curl https://api.foursquare.com/v2/users/self?oauth_token=$token`;
                $json = json_decode($info_contents);
                $userid = $json->response->user->id;

                echo "OK|$userid|$token";
        }
}


?>

Friday, February 11, 2011

Login to twitter via backend using PERL

This is the same from the last post - Login to foursquare via backend using PERL but this time, we're doing it for twitter. Just follow the 4 simple steps below.

1. Install the libraries into your server.
  • LWP::UserAgent;
  • HTTP::Cookies;
2. Initialize the libraries UserAgent and Cookies.

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://m.twitter.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

3. Post your username and password to https://mobile.twitter.com/session and save the cookies.

my $strUser = '<your twitter username>';
my $strPass = '<your twitter password>';

# log-in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
                            ['username' => $strUser,
                             'password' => $strPass,
                             'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

4. You can check if successful or not by accessing https://mobile.twitter.com via GET and print the content.

$response = $lwpua->get('https://mobile.twitter.com', @header);
$form_data = $response->content;

print "$form_data\n\ndone!";


That's it! Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://m.twitter.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

# getting authenticity token
my $response = $lwpua->get('https://mobile.twitter.com/session/new', @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;

my $strUser = '<your twitter username>';
my $strPass = '<your twitter password>';

# log-in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
                            ['username' => $strUser,
                             'password' => $strPass,
                             'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('https://mobile.twitter.com', @header);
$form_data = $response->content;

print "$form_data\n\ndone!";


1;


Hope you like it!! Thank you for reading.

Thursday, February 10, 2011

Login to foursquare via backend using PERL

This is just a simple login request to foursquare via backend using PERL. Just follow the simple steps and the complete code below.

1. Install the libraries needed.
  • LWP::UserAgent;
  • HTTP::Cookies;
2. Initialize UserAgent and Cookies.

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://foursquare.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

3. Post your username and password to https://foursquare.com/mobile/login and save the cookies.

my $strUser = "<your foursquare username>";
my $strPass = "<your foursquare password>";

# log-in to foursquare
my $response = $lwpua->post('https://foursquare.com/mobile/login',
                      ['username' => $strUser,
                       'password' => $strPass], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

4. You can check if successful or not by accessing http://foursquare.com/mobile/ via GET and print the content.

$response = $lwpua->get("http://foursquare.com/mobile/", @header);
my $form_data = $response->content;

print "$form_data\n\ndone!";


That's it! So simple right? Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://foursquare.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your foursquare username>";
my $strPass = "<your foursquare password>";

# log-in to foursquare
my $response = $lwpua->post('https://foursquare.com/mobile/login',
                      ['username' => $strUser,
                       'password' => $strPass], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get("http://foursquare.com/mobile/", @header);
my $form_data = $response->content;

print "$form_data\n\ndone!";


1;


Hope you like it!! Thank you for reading. Please see other post - Login to twitter via backend using PERL

Tuesday, January 4, 2011

How to post tweet on twitter via backend using PERL

Just like from my previous post, you should know how the wap site works, from log-in up to sending your tweets.

If you still have no idea on how the twitter works, just follow the steps below and you will be able to send tweets in minutes.

1. Same on how we do it on facebook, we need to install the following libraries on our server.
  • LWP::UserAgent
  • HTTP::Cookies

2. Once installed, we are now ready to do the coding part. we have to require and initialize the libraries and variables that we will be using.

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);


3. Input your twitter account username, password, and your tweet you wish to be posted.

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";


4. Get the authenticity_token using REGEX from the twitter session url http://mobile.twitter.com/session/new. token will be use as parameter in submitting your credentials to the wap site. i also pasted the form element of the login page below as reference.

=begin
<form action="https://mobile.twitter.com/session" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<input autocapitalize="off" autocorrect="off" id="username" name="username" type="text" />
<input id="password" name="password" type="password" />
<input class="signup" type="submit" value="Sign in" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;


5. Use the token to login by posting it to the form action url above: https://mobile.twitter.com/session and save the cookie for the nest session.

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;


6. Upon submission of credentials, you should be able to log-in successfully. to check it, you should be able to see the "What's happenning?" and the textarea in which you will input your tweet. again, get the authenticity token using REGEX below for the next session.

=begin
<form action="http://mobile.twitter.com/" class="new_tweet" id="new_tweet" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<div class="tweetbox-head">What's happening?</div>
<textarea class="tweet_input" cols="44" id="tweet_text" name="tweet[text]" rows="2"></textarea>
<input class="tweet-btns" type="submit" value="Tweet" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;


7. And now, you are ready to post your tweet. by passing tweet[text] parameter together with the authenticity_token.

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);


8. To get the complete code, please see below. hope you were able to follow. happy coding!!

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";

# get authenticity token
my $response = $lwpua->get('http://mobile.twitter.com/session/new', @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);



1;

Saturday, December 25, 2010

How to post facebook status via backend in PHP

As promised, here's the script on how to submit facebook status using PHP. just follow the simple steps below and you can have a facebook status update on your own website.

1. Again, from my previous post, you should know the structure of the wapsite you wish to access via back-end and for this post, we will access facebook wapsite http://m.facebook.com. check out also my previous post - How to submit facebook status via back-end using PERL

2. Since we are using PHP, we will use CURL to access the site via back-end. make sure you have installed CURL in your server.

3. To start with, input your facebook username/email, password, and status.

$fuser = '<your facebook username/email>';
$fpass = '<your facebook password>';
$status = '<your facebook status>';


4. Initialize CURL as coded below. set the CURLOPT_URL to the login page of the wapsite http://m.facebook.com/login.php to login to the site. set the CURLOPT_POSTFIELDS email and password. then the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/login.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($fuser).'&pass='.urlencode($fpass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/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");
curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
$page = curl_exec($ch); 


5. CURL_EXEC will output the redirected page which you will need to get PARAMETERS in sending STATUS. you can try printing the variable $page so you will know if the return page is successful or not. I pasted a code snippet of the return page below.

<form method="post" id="composer_form" action="/a/home.php?fbb=rbacd82de&amp;refid=7"><input type="hidden" name="fb_dtsg" value="DdtLy" autocomplete="off" /><input type="hidden" name="post_form_id" value="f224790ed71d0fe6565de44f1b4bbe98" /><input type="hidden" name="charset_test" value="€,´,€,´,æ°´,Д,Є" /><div>What&#039;s on your mind?<br /><textarea class="composerInput" name="status" rows="2" onfocus="" onblur=""></textarea></div><input type="submit" value="Share" class="btn btnC" name="update" /></form>


6. You will need parameters such as FORM ACTION, FB_DTSG, and POST_FORM_ID just like in my previous post. to get these parameters, you should use PREG_MATCH.

//this gets the post_form_id value
preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
//we'll also need the exact name of the form processor page
preg_match("/form method=\"post\" id=\"composer_form\" action=\"(.*?)\"/", $page, $form_action);
//we'll also need the value of the fb_dtsg
preg_match("/name=\"fb_dtsg\" value=\"(.*?)\"/", $page, $form_fbdtsg);


7. All parameters will be stored as ARRAY in variables $form_id, $form_action, and $form_fbdtsg. you will use this on the code below to send facebook status.

curl_setopt($ch, CURLOPT_URL, "http://m.facebook.com".$form_action[1]);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'post_form_id='.$form_id[1].'&status='.urlencode($status).'&fb_dtsg='.$form_fbdtsg[1].'&update=Share');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/my_cookies.txt");
$page = curl_exec($ch);


8. Upon executing the CURL, you should expect that your STATUS will be posted in your facebook wall. to get the output and information on your CURL execution, you can print CURL_GETINFO. You can also check for errors by printing CURL_ERRNO and CURL_ERROR.

print_r(curl_getinfo($ch));
echo curl_errno($ch) . '-' . curl_error($ch);


9. To summarize everything, you should have a code like this below. happy coding everyone!!

<?

$fuser = '<your facebook username/email>';
$fpass = '<your facebook password>';
$status = '<your facebook status>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/login.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($fuser).'&pass='.urlencode($fpass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/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");
curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
$page = curl_exec($ch);

preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
preg_match("/form method=\"post\" id=\"composer_form\" action=\"(.*?)\"/", $page, $form_action);
preg_match("/name=\"fb_dtsg\" value=\"(.*?)\"/", $page, $form_fbdtsg);

curl_setopt($ch, CURLOPT_URL, "http://m.facebook.com".$form_action[1]);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'post_form_id='.$form_id[1].'&status='.urlencode($status).'&fb_dtsg='.$form_fbdtsg[1].'&update=Share');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/my_cookies.txt");
$page = curl_exec($ch);

print_r(curl_getinfo($ch));
echo curl_errno($ch) . '-' . curl_error($ch);

?>

Thursday, December 23, 2010

How to post facebook status via backend in PERL

We know that facebook site is a secured and very strict with regards to their website and other site components. There is so much happening on the site that users doesn't realize it changes constantly and that is also for security reason, why? that is because hackers do some research, checking the site constantly as well and if your site is not changing, they can come up with a plan and boom!! before you know it, you're doom already.

Enough with the applaud to the company coz they were great already.

I'm not here to lecture about hacking, but how to submit facebook status right? so, just follow the steps below and you can have a BOT that will send facebook status without human intervention.

1. First thing you have to do is to know the structure of the wap site, this time the facebook wap site http://m.facebook.com

2. Since we are using PERL, we have to install some libraries for sending HTTP request and cookies. install the libraries below:
  • LWP::UserAgent
  • HTTP::Cookies

3. After installing the 2 libraries into your server, we are now ready to do the coding. The code below is just a standard coding that we do in PERL.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;


4. After we require the libraries, we need to initialize the variables we need.

my $lwpua = LWP::UserAgent->new;

5. Set your facebook username/email, password, and your status. please see below.

my $strUser = "<your facebook username/email>";
my $strPass = "<your facebook password>";
my $strStatus = "<your facebook status>";


6. Set up user agent that we will use to send HTTP request.

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://m.facebook.com/','User-Agent' => $user_agent);


7. Set up cookie file and jar.

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);


8. Setup the code for log-in to facebook. Please take note that you should know the link of the login page of the site which is http://m.facebook.com/login.php. The important thing here is to look for the FORM element in which the site is submitting the credentials. You also have to get all the important INPUT parameters for submission to the FORM. I pasted here the FORM element of the login page source as of today as reference. Below also are the ONLY details you need to login.

=begin
<form method="post" action="https://login.facebook.com/login.php?m=m&amp;refsrc=http%3A%2F%2Fm.facebook.com%2login.php&amp;fbb=rac4881b1&amp;refid=9">
<input class="input" name="email" value="" type="text"/>
<input class="input" name="pass" type="password"/>
<input type="submit" value="Log In" class="btn btnC" name="login"/>
</form>
=cut

# logging in to facebook
my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);


9. After logging in, we have to extract the COOKIES and use it on our next SESSION or PAGE.

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;


10. After saving the COOKIES, accessing the facebook home page should direct you to the home page where in you can send your STATUS. You can check that if you print the $response->content. I also pasted the code snippet of the content below as reference.

$response = $lwpua->get('http://m.facebook.com/home.php', @header);
my $form_data = $response->content;

=begin
<form method="post" id="composer_form" action="/a/home.php?fbb=r488fb708&amp;refid=7"><input type="hidden" name="fb_dtsg" value="DdtLy" autocomplete="off" /><input type="hidden" name="post_form_id" value="726fdf3c15403500a70f64960565e305" /><input type="hidden" name="charset_test" value="€,´,€,´,æ°´,Д,Є" /><div>What&#039;s on your mind?<br /><textarea class="composerInput" name="status" rows="2" onfocus="" onblur=""></textarea></div><input type="submit" value="Share" class="btn btnC" name="update" /></form>
=cut


11. Same thing here with the login page but this time, we need to know how the page sends a status message. find the FORM that submits STATUS. please take note that the site is frequently changing so you should know how to do the REGEX to catch all the PARAMETERS you need and for the benefit of this post, the above content is the updated content as of today and my REGEX below should be able to catch parameters such as: FORM ACTION, FB_DTSG, and POST_FORM_ID.

$form_data =~ s/\n//g;
$form_data =~ /form method="post" id="composer_form" action="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"(.*?)name="post_form_id" value="(.*?)"/ig;

my $form_action = $1;
my $form_fbdtsg = $3;
my $form_id = $5;


12. Send now the STATUS message with the PARAMETERS needed below.

@header = ('Referer' => 'http://m.facebook.com/',
           'User-Agent' => $user_agent);

$response = $lwpua->post('http://m.facebook.com'.$form_action,
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'status' => $strStatus,
                            'update' => 'Share'], @header);

$form_data = $response->content;
unlink($cookie_file);

1;


13. And, that's it!! below is the whole script. hope you were able to get it. next will be in PHP. yeah men!!

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $strUser = "<your facebook username>";
my $strPass = "<your facebook password>";
my $strStatus = "<your facebook status>";

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://m.facebook.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;
$response = $lwpua->get('http://m.facebook.com/home.php', @header);

my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /form method="post" id="composer_form" action="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"(.*?)name="post_form_id" value="(.*?)"/ig;

my $form_action = $1;
my $form_fbdtsg = $3;
my $form_id = $5;

@header = ('Referer' => 'http://m.facebook.com/',
           'User-Agent' => $user_agent);

$response = $lwpua->post('http://m.facebook.com'.$form_action,
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'status' => $strStatus,
                            'update' => 'Share'], @header);

$form_data = $response->content;
unlink($cookie_file);

1;

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.