I am using Facebook SDK to post some test wall post on my own Facebook page. What i want is to post on my facebook page every 8 hours using PHP CRON script and for that i have to bypass the Facebook login dialog page, So does anyone know the way to authenticate from command line or on air?
Authenticating as a Page will give you an access token which you can save it in your database and then perform various tasks using PHP.
This is helpful for doing various things using cron, Such as scheduling posts, maintain multiple pages, post to multiple pages at once, upload photos and lot of other activities using Graph API. Check their docs for more information on how to do that.
Note: You just have to authenticate your app once and save your page access token key, once you do this, you don't have to login again and you can just use your access token to perform various tasks on your page.
Facebook provide Access Token for a user to use the Facebook app. For the First time , user has to login through facebook login, after login to the site, it will ask the permission to access the App. Once User Accept then facebook will return you a code throgh url. You have to take the code and use that to get access token
by using following code
$url = "https://graph.facebook.com/oauth/access_token?client_id=". $yourappId ."&redirect_uri=". urlencode($this->redirect_url) ."&client_secret=". $youappsecret."&code=". $code;
$auth_token = $this->getContents($url);
$str = explode('=',$auth_token);
$token = explode('&expires', $str[1]);
Here $token will have the access token of an user, u can store that token in ur local db and use that token to post a message to facebook wall. its simple.. thats all.
To Post a message on Fb Wall
$fb_id = "User_fb_id"
$access_token = "User_Access_Token_Take by Above code"
$msg = "Message_to_post"
$img_path = "Image_Path"
$facebook = new Facebook(array(
'appId' => $this->appId,
'secret' => $this->secret,
'cookie' => true));
if($msg != NULL) {
$attachment = array(
'message' => $msg,
'name' => 'NHM',
'picture' => $img_path);
}
try {$result = $facebook->api('/'. $fb_id . '/feed/',
'post',
$attachment);
if(isset($result['id']))
return true;
else
return false;
} catch(FacebookApiException $e) {
return $e->getMessage();
}
Here you have to user Facebook User Id. To get User Id use the following Code
$url = "https://graph.facebook.com/me?access_token=". $access_token;
$userInfo = $this->getContents($url);
$userInfo = json_decode($userInfo, true);
public function getContents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec ($ch);
curl_close ($ch);
return $content;
}
Try this . Let me know If any issues
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With