Skip to content

Instantly share code, notes, and snippets.

@vikas5914 vikas5914/index.php
Created May 28, 2016

Embed
What would you like to do?
Fix Some Noob's code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('facebook/src/Facebook/autoload.php');
// some settings you might want to change
$params = array(
"app_id" => "xxxxxxxxxxxxxxxxxxxxx",
"app_secret" => "xxxxxxxxxxxxxxxxxxx",
"page_id" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"access_token" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$post = array(
"message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
"link" => "http://www.gadgetrolley.com/Store/",
"picture" => "http://www.gadgetrolley.com/Store/image/data/gt.png",
"name" => "Online Mobile and Electronic Store",
"caption" => "www.gadgetrolley.com",
"description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);
// Create a facebook instance
$fb = new Facebook\Facebook ([
'app_id' => $params['app_id'],
'app_secret' => $params['app_secret'],
'default_graph_version' => 'v2.2',
]);
// Trying to get our own user name and id
try {
$response = $fb->get('/' . $params['page_id'] . '?fields=id,name', $params['access_token']);
}
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;
}
$user = $response->getGraphUser();
// Debug output
//print_r($user);
//exit;
if ($user) {
try {
$post_id = $fb->post('/' . $params['page_id'] . '/feed', $params, $params['access_token']);
}
catch (Exception $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $fb->getLogoutUrl();
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://example.com/', $permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.