How To Post To Facebook With PHP

By Xandermar LLC, October 23, 2023

To post to a Facebook page using PHP, you can use the Facebook Graph API. Here's a basic PHP class that demonstrates how to post to a Facebook page:


class FacebookPagePoster {
   private $accessToken;
   private $pageId;

   public function __construct($accessToken, $pageId) {
       $this->accessToken = $accessToken;
       $this->pageId = $pageId;

   public function postToPage($message) {
       $url = "{$this->pageId}/feed";

       $data = array(
           'message' => $message,
           'access_token' => $this->accessToken,

       $options = array(
           'http' => array(
               'method' => 'POST',
               'content' => http_build_query($data),

       $context = stream_context_create($options);
       $result = file_get_contents($url, false, $context);

       // Handle the response (you can add error checking here)
       if ($result === false) {
           return false; // Posting failed
       } else {
           return true; // Posting successful

// Usage example:

$poster = new FacebookPagePoster($accessToken, $pageId);
$message = 'Hello, Facebook!';
if ($poster->postToPage($message)) {
   echo 'Posted successfully.';
} else {
   echo 'Posting failed.';

Make sure to replace 'YOUR_FACEBOOK_ACCESS_TOKEN' and 'YOUR_FACEBOOK_PAGE_ID' with your actual Facebook access token and page ID.

Note that you need to obtain a valid Facebook access token with the necessary permissions to post to the page you want. Additionally, this example uses the Facebook Graph API, so you should keep your PHP environment up to date with any changes Facebook makes to its API.

New Articles Alert

Associated Tags

This content is the only content that uses this tag. More coming soon!