Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Facebook PHP example.
<?php
/**
* A simple Facebook PHP example.
*
* - This is not a "Facebook SDK".
* - This example uses Curl, Hash, JSON, Session extensions.
* - This does not use the JavaScript SDK, nor the cookie set by it.
* - This works with Canvas, Page Tabs with IFrames, the Registration Plugin
* and with any other flow which uses the signed_request.
*
* @author Naitik Shah <n@daaku.org>
*/
function idx($array, $key, $default=null) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
class FacebookApiException extends Exception {
public function __construct($response, $curlErrorNo) {
$this->response = $response;
$this->curlErrorNo = $curlErrorNo;
}
}
class Facebook {
public function __construct($opts) {
$this->appId = $opts['appId'];
$this->secret = $opts['secret'];
$this->accessToken = idx($opts, 'accessToken');
$this->userId = idx($opts, 'userId');
$this->signedRequest = idx($opts, 'signedRequest', array());
$this->maxSignedRequestAge = idx($opts, 'maxSignedRequestAge', 86400);
}
public function loadSignedRequest($signedRequest) {
list($signature, $payload) = explode('.', $signedRequest, 2);
$data = json_decode(self::base64UrlDecode($payload), true);
if (isset($data['issued_at']) &&
$data['issued_at'] > time() - $this->maxSignedRequestAge &&
self::base64UrlDecode($signature) ==
hash_hmac('sha256', $payload, $this->secret, $raw=true)) {
$this->signedRequest = $data;
$this->userId = idx($data, 'user_id');
$this->accessToken = idx($data, 'oauth_token');
}
}
public function api($path, $params=null, $method='GET', $domain='graph') {
if (!$params) $params = array();
$params['method'] = $method;
if (!array_key_exists('access_token', $params) && $this->accessToken)
$params['access_token'] = $this->accessToken;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HTTPHEADER => array('Expect:'),
CURLOPT_POSTFIELDS => http_build_query($params, null, '&'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_URL => "https://$domain.facebook.com$path",
CURLOPT_USERAGENT => 'nshah-0.1',
));
$result = curl_exec($ch);
$decoded = json_decode($result, true);
$curlErrorNo = curl_errno($ch);
curl_close($ch);
if ($curlErrorNo !== 0 || (is_array($decoded) && isset($decoded['error'])))
throw new FacebookApiException($decoded, $curlErrorNo);
return $decoded;
}
public static function base64UrlDecode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
}
function FB() {
$fb = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET',
));
header('P3P: CP=HONK'); // cookies for iframes in IE
session_start();
if (isset($_POST['signed_request'])) {
$fb->loadSignedRequest($_POST['signed_request']);
$_SESSION['facebook_user_id'] = $fb->userId;
$_SESSION['facebook_access_token'] = $fb->accessToken;
} else {
$fb->userId = idx($_SESSION, 'facebook_user_id');
$fb->accessToken = idx($_SESSION, 'facebook_access_token');
}
return $fb;
}
$fb = FB();
$registration_plugin_url =
'http://www.facebook.com/plugins/registration.php?' .
http_build_query(array(
'client_id' => $fb->appId,
'redirect_uri' => "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}",
'fields' => 'name,email'));
?>
<pre><?php print_r($fb); ?></pre>
<?php if (!$fb->userId) { ?>
<h3>Registration</h3>
<iframe src="<?php echo $registration_plugin_url; ?>"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="600"
height="330">
</iframe>
<?php } else { ?>
<h3>API Call</h3>
<pre><?php print_r($fb->api('/me', array('fields' => 'friends'))) ?></pre>
<?php } ?>
@hvianna

This comment has been minimized.

Copy link

hvianna commented Sep 7, 2011

Thanks man, this was a real time saver! Facebook's PHP SDK is so cluttered >.<

@erich1

This comment has been minimized.

Copy link

erich1 commented Oct 13, 2011

You did a great job!!!!!!
It works perfect on PC using various browsers, Safari included.

I just have a problem getting this running at Safari on iPad2 with iOS 5.0: At that point when FB() is called wether $_SESSION nor $_POST is filled out. Both variables are empty, so my application keeps displaying the registration form. Do you have any idea what is going wrong here?

@ksrea

This comment has been minimized.

Copy link

ksrea commented Jan 11, 2013

how do you install this app on your facebook page ?
is there instructions somewhere ?
thanks,
kevin rea

@caneco

This comment has been minimized.

Copy link

caneco commented Jul 9, 2013

One question… I've grant permissions, and then revoke them on the (https://www.facebook.com/settings/?tab=applications) page.

But the user its still in session. I've tried to destroy the session but with no luck. Any thoughts?

@highborg-justin

This comment has been minimized.

Copy link

highborg-justin commented Jan 10, 2014

You are great!!! my 2 weeks struggle has come to an end :) thanks a lot

@1veena

This comment has been minimized.

Copy link

1veena commented Apr 18, 2017

please tell how to registrer user in an app with facebook in php

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.