I made this PHP script that fetches messages to be posted at regular intervals to a Facebook Page that I administer.
My script is working fine, but depends on me as a user being logged into Facebook. I would like this script to run as a cron job so i fear the script will fail to work if i'm logged out.
How can i make it work even if i'm not logged into Facebook?
Note that I created a Facebook application as requested to be able to use the Facebook api. Is there a way to post as the Facebook application perhaps?
Here is my code, in case it helps.
require_once('config.inc.php');
require '_classes/facebook-php-sdk/src/facebook.php';
$homeurl = 'http://domain.com/to-facebook/index.php';
$post_url = '/'.PAGEID.'/feed';
// The message
$msg_body = array(
'message' => 'hello world',
);
// Post to Facebook
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
// Get User ID
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$postResult = $facebook->api($post_url, 'post', $msg_body );
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}else{
// I would like never to come to this point...
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>'publish_stream,manage_pages,publish_actions,status_update,offline_access'));
header('Location: ' . $loginUrl);
}
if($postResult)
{
echo '<h1>Your message is posted on your facebook wall.</h1>';
}
* update * I tried the cronjob and unfortunately, after a while I had the "Error validating access token: Session has expired at unix time" message. I'm puzzled. What am i doing wrong?