Automate your social media presence with PHP to automatically publish posts on

I'm currently developing a PHP script to automatically share posts on Facebook. The script runs perfectly when executed directly from the browser, but when I enable cron jobs it executes the file without sharing on my Facebook wall. I'm unsure of what might be causing this issue. Here is a snippet of my script:

<?php
ob_start();
require_once('facebookapi/site-primary-config.php');
require_once('facebookapi/facebook.php');

// configuration
 $appid = 'xxxxx';
 $appsecret = 'xxxxx';
 $pageId = 'xxxx';

//Get Load from Social Video ID 
$get_link_sql = mysqli_query($conn,"SELECT tblmevids.vid_code as video_tbl_code,
tblmevids.vid_title as video_tbl_title,
tblmevids.vid_seo_descp as video_tbl_description,
tblmevids.vid_slug as video_tbl_slug,
tblsocial_share.vidsc_code as vid_social_code,
tblsocial_share.vid_fb_sstat as vid_social_fb_status
FROM tblmevids
JOIN tblsocial_share ON tblmevids.vid_code = tblsocial_share.vidsc_code
WHERE tblmevids.vid_act_stat = '1' AND tblsocial_share.vid_fb_sstat = '0' LIMIT 1");
$count_sql = mysqli_num_rows($get_link_sql);
$link_row = mysqli_fetch_array($get_link_sql);
$selected_video = $link_row['video_tbl_code'];
$selected_title = $link_row['video_tbl_title'];
$selected_description = $link_row['video_tbl_description'];
$selected_slug = $link_row['video_tbl_slug'];

if($count_sql > 0 ) {
        //Grab Video Details
            $msg = $selected_title.' - Watch Now at '.$site_baseurl.'watch?v='.$selected_video;
            $title = $selected_title;
            $uri = $site_baseurl.$selected_slug;
            $desc = $selected_description;
            $pic = $site_baseurl.'video_thumbs/'.$selected_video.'.jpg';
            $action_name = 'Go to mywebsite.com';
            $action_link = 'http://mywebsite.com';

            echo $msg."<br/>".$title."<br/>".$uri."<br/>".$desc."<br/>".$pic."<br/>".$action_name."<br/>".$action_link."<br/>";

            //Start FB Sharing
            $facebook = new Facebook(array(
                'appId' => $appid,
                'secret' => $appsecret,
                'cookie' => false,
            ));
            $user = $facebook->getUser();
            
            if ($user) {
                try {
                    $page_info = $facebook->api("/$pageId?fields=access_token");
                    if (!empty($page_info['access_token'])) {
                        $attachment = array(
                            'access_token' => $page_info['access_token'],
                            'message' => $msg,
                            'name' => $title,
                            'link' => $uri,
                            'description' => $desc,
                            'picture'=>$pic,
                            'actions' => json_encode(array('name' => $action_name,'link' => $action_link))
                        );

                        $status = $facebook->api("/$pageId/feed", "post", $attachment);

                        $get_perfect_status = '1';
                        $updates = array();

                        if (is_numeric($get_perfect_status))
                            $updates[] = '`vid_fb_sstat` ="'.$get_perfect_status.'"';
                            $updates = implode(', ', $updates); 
                            $sql = "UPDATE `tblsocial_share` SET $updates WHERE vidsc_code = '$selected_video'";
                            $result=mysqli_query($conn,$sql);

                            if($result){
                                echo "Shared on Facebook and updated successfully";
                            } else {
                                echo "There was a problem in sharing";
                            }
                     } else {
                         $status = 'No access token received';
                     }
                 } catch (FacebookApiException $e) {
                     error_log($e);
                     $user = null;
                 }
             } else {
                     header("Location:{$facebook->getLoginUrl(array('scope' => 'publish_actions,manage_pages'))}");
             }

            echo $status;

    } else {
        echo "not found";
    }
 ?>

Answer №1

When you schedule it as a cron job, the script may not have access to a logged-in user. However, if you run it in your browser while being authenticated on Facebook, the script can fetch the user ID correctly. To remedy this situation, you need to manually specify your user ID retrieved from Facebook.

$user = $facebook->getUser();

Replace the above code snippet with:

$user = 'xxxxx';

To find your user ID, just insert an echo statement after retrieving the user ID:

echo $user."\n";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Redirecting using PHP in an Ajax request

I'm struggling with an Ajax call that sends login form values to a PHP file. If the username and password are incorrect, I want to update the div id= #phplogin above the form with an error message. The issue arises when the credentials are correct be ...

Sending JSON data from an AJAX request to a PHP script

JavaScript file: var jsonData = []; var dataObject = new Object(); dataObject.name = "bob"; dataObject.age = "000"; dataObject.test = "test"; var json = JSON.stringify(dataObject); jsonData.push(json); $.ajax({ type: "POST", ...

Using PHP to pass both string and integer values into a JavaScript function

I am attempting to pass both a string and an integer into the same function, but I am running into issues with quotes. After some troubleshooting, I realized that the problem lies in the echo $q->info part of my code - I need to use double quotations fo ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

Is it possible for Susy to output a pixel-based span?

As a newbie to Susy, I hope you don't mind if I ask a seemingly silly question... I'm trying to figure out how to calculate responsive padding within a Susy grid. The standard formula is: (target / context) x 100. Is there a way for Susy to pr ...

Extract only one term in PHP

I've searched high and low but haven't found a solution that fits my needs. All I want to keep is the word you. $words = "you,us,them,our"; $keep = "you,"; The code provided seems to do the opposite of what I need: $words = str_replace("$kee ...

Struggling with breaking down passport.js into modules in node.js

Hey there, I'm facing a bit of an issue with my login route: var express = require('express'); var router = express.Router(); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; re ...

Converting the creation time from JSON format and replacing any special characters in the input

I'm facing a challenge in describing this. I am using the Facebook graph to showcase my pages' activity on Facebook/Twitter (via Facebook) on a website. Everything is going smoothly, except for formatting the created_time data properly. I have ve ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

Table for Selecting Radio Buttons in Form Submission

When creating a table of radio buttons, each user can only choose one radio button per column. I assigned the same name to each column - for example: if there are 20 radios in each line, then each column is named b1, b2, b3, b4... b20. The selection is wor ...

The Complexity of Many-to-Many Relationships in Doctrine 2

As a beginner with Zend Framework 2, I recently encountered Doctrine 2 and would like to integrate it into my first project. Despite spending several days on it, I am struggling with the following issue: I have three tables: Advert advert_id advert_tit ...

Working with PHP to retrieve values from an array object

I have the following array: businesscommercialArray = { 40E: { id: 94, swift_code: "40E", status: 1 }, 43P: { id: 106, swift_code: "43P", status: 2, note: "Allowed (INSTEAD OF EXIST ...

PHP-based turn-based web game - encountering communication challenges

I am currently developing a PHP5-based turn-based web game. The game itself is quite straightforward, resembling a board game where two players join a session and take turns playing until there is a winner. Here is the issue I'm facing: User A a ...

Create RESTful routes based on the attributes of the resource

When dealing with a User entity and needing to retrieve its data using different criteria or routes, such as by id or username, what is the recommended approach for naming these specific endpoints: GET /users/:id GET /users/username/:username GET /users/ ...

An array nested within another array

Since 9am, I have been struggling to find the results I need even after extensive searching. The issue lies with an array that is dynamically created using PHP. array_push($this->product_info, $subline1, $subline2, $subcarving ...

Issue with PHP Soap Client Authentication Key

Seeking assistance from PHP experts. Despite my familiarity with PHP, I am struggling to identify the problem in this code. We are working with an external MSSQL Database owned by our client. A CRM solution is used to generate a license key for products u ...

Using PHP to decode a JSON array (Troubleshooting issues with Ajax JSON POST to PHP)

I am new to PHP and I have a jQuery/JavaScript based application that involves finding nearby places and presenting the results in a sorted order. I am attempting to move the sorting function from the HTML page to server-side PHP. This process includes ...

Obtaining the latest record ID from MySQL using node.js

I am currently working on a project where I need to add new user information to a MySQL database. I'm looking for a way to retrieve the ID of the most recently added record so that I can create login details for the user. The environment in which this ...

Here is a guide on determining the date variance in PHP by leveraging jQuery

I have been attempting to use the jQuery change function to calculate the variance between two dates, but I am encountering a problem as the code seems to be running smoothly without returning any results... <input type="text" name="datte1" class="form ...

What is the process for redirecting users after they log in to Codeigniter?

After a user logs into their account, I want them to be redirected back to the page they were on instead of the members area section. Below is the specific page I want the visitor to see post-login: http://www.localhost.com/folder/this-is-the-restricted- ...