check if facebook post exists before making api call - php

I am getting a fatal php error: "Fatal error: Uncaught GraphMethodException: Unsupported get request. thrown in /facebook-php-sdk/src/base_facebook.php on line 1340", when making an api call on posts that have been deleted on facebook. i want to be able to delete the post from my database if the post has been deleted from facebook and also remove this fatal error. my api call is in a while loop to return the top posts (ranked on comments, shares and likes). i need to check for the existence of the post before returning the post and delete it from database if removed from facebook.
$get_content_db_info = mysqli_query($dbc , "SELECT * FROM `content`");
echo '<table id="leaugeTable"><thead><tr><th>Name</th><th>Post ID</th><th>Facebook ID</th><th>Score</th></tr></thead><tbody>';
while($row = mysqli_fetch_array($get_content_db_info)){
// then your for loop
$fbApiGetPosts = $facebook->api('/'.$row["fb_id"].'_'.$row["post_id"]);
$fbApiGetShares = $fbApiGetPosts["shares"];
$shareCount = $fbApiGetShares["count"];
$fbApiGetLikes = $facebook->api('/'.$row["post_id"].'/likes');
$countLikes = $fbApiGetLikes["data"];
$likesResult = count($countLikes);
$fbApiGetComments = $facebook->api('/'.$row["post_id"].'/comments');
$countComments = $fbApiGetComments["data"];
$cc = count($countComments);
$score = $likesResult + $shareCount * 2 + $cc * 3;
echo '<tr><td>'.$row["first_name"].' '.$row["last_name"].'</td><td>'.$row["post_id"].'</td><td>'.$row["fb_id"].'</td><td class = "sortCol">'.$score.'</td></tr>';
}
this is my first facebook project and dont know how to go about this.

If the post has been deleted from facebook, you'll see the Fatal error: Uncaught GraphMethodException: Unsupported get request. error. What you can do is:
while($row = mysqli_fetch_array($get_content_db_info)){
try {
// your original while code
} catch ( Exception $e ) {
// error from facebook, post is likely to be deleted
if ( $ex->getMessage() === 'Unsupported get request.' ) {
// delete post from database
}
}
}
The try...catch statement will catch any errors, including Unsupported get request., where you can then delete the post from the database, without affecting the rest of the flow.

Related

API Pinterest in PHP - Login failed

I used seregazhuk/php-pinterest-bot (in Symfony 4) to add pin on Pinterest (v5.9.0). When I tried to log in, something failed. Here my code:
$mail = getenv("PINTEREST_MAIL");
$pwd = getenv("PINTEREST_PASSWORD");
$bot = PinterestBot::create();
$res = $bot->auth->login($mail, $pwd); // return false
$bot->getLastError(); // return NULL
$boards = $bot->boards->forUser($username); // failed
When I look in logs, I've got the following error:
Uncaught PHP Exception seregazhuk\PinterestBot\Exceptions\AuthRequired: "Error calling seregazhuk\PinterestBot\Api\Providers\Pins::create method. You must log in before."
I've already checked my mail, my username, and my password. I can connect successfully with them.
What's wrong?
Looks like the lib you are using hasn't been working for a while:
https://github.com/seregazhuk/php-pinterest-bot/issues/442
Issue was solved a few days ago after the publication of a new release 5.9.1. Now, you can use it again. The following method returns true as it should be:
$res = $bot->auth->login($mail, $pwd); // return true

In Zend framework getting 500: Internal Server Error

I have one issue in zend framework got stuck due to this error
I developed Rest API but POST urls not working
500: Internal Server Error
but all get urls are working
When i debug all code its showing me error in AbstractTableGateway.php at line no 290 in executeInsert function
$result = $statement->execute();
full function code
protected function executeInsert(Insert $insert)
{
$insertState = $insert->getRawState();
if ($insertState['table'] != $this->table) {
throw new Exception\RuntimeException('The table name of the provided Insert object must match that of the table');
}
// apply preInsert features
$this->featureSet->apply('preInsert', array($insert));
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
$this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue();
// apply postInsert features
$this->featureSet->apply('postInsert', array($statement, $result));
return $result->getAffectedRows();
}
After this line code not working means its showing above error

Soundcloud API Check if a user is following another user

I'm trying to figure out if a user is following another user on Soundcloud using the Soundcloud API and php.
So far I came across a solution which would either return an object (user) or a 404 error:
$test = json_decode($client->get('/users/{id1}/followers/{id2}'));
I've tried it multiple times with different user IDs but I always receive a the following error message:
'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
I know that this is supposed to be the error message which informs me that user2 is not following user1. However I've tried this snippet with ids where I know a reciprocal following exists for sure.
Any suggestions on how this can be solved?
Update (21.05.15):
I've read through some of the Soundcloud documentation and cam across a code snippet:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// Follow user with ID 3207
$client->put('/me/followings/3207');
// Unfollow the same user
$client->delete('/me/followings/3207');
// check the status of the relationship
try {
$client->get('/me/followings/3207');
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
if ($e->getHttpCode() == '404')
print "You are not following user 3207\n";
}
?>
This is pretty much what I was referring to. However if I open a php page with this script the result is always one of three cases:
You are not following user 3207 (expected output)
No output (I'm following the user)
Uncaught exception 'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
The third option is either referring to $client->put or $client->delete
Here is how i would do this:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud(
'xxxxxxxxxxxxxxxxxxx160', 'xxxxxxxxxxxxxxxxxx34dd1 ');
$userid = 1672444;
$followerid = 383228;
$yesno = '';
try {
$response = json_decode($client->get('users/'.$userid.'/followers'), true);
$yesno = IdInArray($response, $followerid);
echo $yesno;
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
function IdInArray($response, $followerid){
echo $followerid.'<br/>';
for($i = 0; $i < count($response); ++$i) {
if($response[$i]['id'] == $followerid){
return 'yolo';
}
else{
return 'nolo';
}
}
}
?>

Call to a member function processqueue() on a non-object

I'm trying to run this file, this file sends emails and updates tables etc (Various tasks).
But, I'm getting this error
Fatal error: Call to a member function processqueue() on a non-object in /home/novosctn/public_html/user/cron_email_handler.php on line 14
I've gone through various questions here but none of them helped me.
What wrong am I doing ?
Any suggestions are appreciated.
DB Structure
indexid(int unsigned) others
1 xyz
2 asa
The file.
<?php
include 'dbconnector.php';
include 'class/class.user.php';
//this file would loop through the Queued rows in the messagequeue and process them.
//first, get all the unprocessed queue.
try
{
$statement = $conn->query("SELECT * from messagequeue where currentstatus = 'Queued'");
$statement->setFetchMode(PDO::FETCH_OBJ);
while($q = $statement->fetch())
{
//now process
if($user->processqueue($q->indexid))
{
//$user->notifyAdmin();
//$user->notifyUser();
$i=2;
//notify admin of a successful queue complete
//notifyuser that a particular queue was not completed.
echo $q->indexid . "was completed";
}
else
{
$i=1;
//the particular que was not completed.
//notify admin about this
echo $q->indexid . "was not completed";
}
}
}
catch(PODException $e)
{
echo $e->getMessage();
}
?>

How to get a message in a variable if the page contains an error?

While we run an web application some page may contain error and some page maynot contain error,
I want to get a notification if the page contains some error ,If there is an error we can see the error in the page, but can we set any value to a variable if the page contains error.. such that we can get the notification that there is an error .
I want to get the notification since i want to create an error log,If we can set the variable with some value then we can use some condition to create a logfile
How can we do that?
There is several ways to do it. One is to setup a custom error handler. PHP will trap most errors raised during script execution and pass it to your custom handler then. What you do inside the handler is up to you. You can write to a log and then redirect to somewhere else or whatever you want.
If you are talking about Exceptions, then wrap code that can break in try/catch blocks. If an error occurs, handle the exception the catch block. What you put in there is again up to you.
Go through the linked pages to learn how this works. Catching an error, setting a variable and writing to a log are three distinct things. Isolate and solve them one by one.
You could also consider using a try { } catch { } block and writing exceptions to error log in catch { } part. Like this:
try {
$db = new MyDb('127.0.0.1', 'root', 'root');
if (false === $db) {
throw new Exception ('Could not connect to the database.');
}
$row = $db->getTable('table_name')->getRowByColumn('id', $_GET['id']);
if (null === $row) {
throw new Exception ('Row with id ' . $_GET['id'] . ' not found.')
}
// and so on
} catch (Exception $e) {
$fp = fopen('logs/error.txt', 'w');
fwrite($fp, date('l jS \of F Y h:i:s A') . ': ' . $e->getMessage() . "\n");
fclose($fp);
}
You get the idea.
Instead of just a date of error you could also append a login of signed in user if the script is in authentication protected area so you know which user got that error.

Categories