Created
May 28, 2016 11:30
-
-
Save vikas5914/e0dcfd531e9e9e9c831821e17218df92 to your computer and use it in GitHub Desktop.
Fix Some Noob's code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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