How to Auto Publish with PHP to Facebook Wall

Hello. I am still relatively new to php, and I am trying to utilize this script to publish content to a facebook wall.

However, when I run the script, it does not publish to the facebook wall and all that prints is: Array ([ID]=>[(facebook page id)_(random number that changes upon page refresh)])

My intention is to eventually use a version of this script to enable multiple individuals to auto-publish content to facebook.

If anyone has any ideas on what I am doing wrong and how I can make this script publish to a facebook wall, I would appreciate it.

For reference, I am using the recommended GitHub facebook phpSDK, which can be found here:
    // Include facebook class (make sure your path is correct)  
    $userID ='xxxx'; //the user id of the account to publish to
	$accessToken ='xxxx'; //access token granting permission
	$message ='This is a Test'; 
    // Create our Application instance (replace this with your appId and secret).  
    $facebook = new Facebook(array(  
      'appId'  => 'xxxx',  
      'secret' => 'xxxx',  
      'cookie' => true,  
    $post = array('access_token' => $accessToken, 'message' => $message . date('Y-m-d'));  
    $res = $facebook->api('/'.$userID.'/feed','POST',$post);  
    } catch (Exception $e){  
        echo $e->getMessage();  
    }  ;

Open in new window

Who is Participating?
Mark GilbertConnect With a Mentor Senior Performance EngineerCommented:

the first thing I see is that your call to the fb api is incorrect. Here's a sample of what it should look like using the latest version of the PHP SDK:

$post_id = $facebook->api('/me/feed', 'post', array('name'=>$title, 'link'=>$link, 'picture'=>$picture,'caption'=>$caption,'description'=>$description, 'actions'=>array('name'=>$actionname, 'link'=>$link)));

Open in new window

You will need to define the values of the variables so that they are referenced correctly at the time you do a wallpost.

The other thing I noticed is that you aren't checking for the publish_stream permission. Your app must ask for implicit permission to use this as it doesn't come enabled out of the box. To get the permissions you can use something like:

$perms = $facebook->api("/me/permissions/");

Open in new window

Then check for the perms:

if(array_key_exists('publish_stream', $perms['data'][0])){
// publish perms are found
} else{ 

$url = $facebook->getLoginUrl(array('scope' => 'publish_stream'));
header("Location: $url");

Open in new window

The documentation on has been greatly improved so you should find everything you need.

Hope this helps.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.