Simple example to post to a Facebook fan page via PHP?
Here is an example of how you can post to a Facebook fan page using the Facebook PHP SDK:
Here is an example of how you can post to a Facebook fan page using the Facebook PHP SDK (facebook/graph-sdk):
Simple example to post to a Facebook fan page via PHP
<?php
require_once __DIR__ . '/vendor/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => 'YOUR_APP_ID',
'app_secret' => 'YOUR_APP_SECRET',
'default_graph_version' => 'v19.0',
]);
$pageAccessToken = 'YOUR_PAGE_ACCESS_TOKEN';
try {
$response = $fb->post(
'/YOUR_PAGE_ID/feed',
[
'message' => 'Hello, world!',
],
$pageAccessToken
);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit();
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit();
}
$graphNode = $response->getGraphNode();
if ($response->getStatusCode() == 200) {
echo 'Successfully posted! Post ID: ' . $graphNode->getField('id');
} else {
echo 'Failed to post.';
}
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
Replace the placeholders YOUR_APP_ID, YOUR_APP_SECRET, YOUR_PAGE_ACCESS_TOKEN, and YOUR_PAGE_ID with your own values. Make sure you have the Facebook PHP SDK installed in your project via Composer: composer require facebook/graph-sdk.
Note: Make sure you have correct permissions to post on the page. For modern Graph API versions, the page access token requires the pages_manage_posts permission. (Note: In production environments, consider logging errors instead of echoing them.)