Skip to content

Instantly share code, notes, and snippets.

@tovask
Last active January 17, 2018 15:05
Show Gist options
  • Save tovask/eb3119e85ccb4bd72273fd2adf4ca612 to your computer and use it in GitHub Desktop.
Save tovask/eb3119e85ccb4bd72273fd2adf4ca612 to your computer and use it in GitHub Desktop.
example user authentication with facebook
<?php
/*
https://developers.facebook.com/docs/facebook-login/
https://developers.facebook.com/docs/graph-api/reference/v2.11/
https://developers.facebook.com/apps/{app-id}/fb-login/
The redirect url in the app's settings (link above) must be exactly the same (including parameters)!
*/
header('Expires: Sun, 01 Jan 1980 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
print '<!DOCTYPE html><body><pre>'."\n\n";
$client_id = '{app-id}';
$client_secret = '{app-secret}';
$self_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$redirect_url = $self_url.'?fb_redirect=true';
if(isset($_GET['fb_redirect']) && $_GET['fb_redirect']==='true'){
if(!isset($_GET['code'])){
print 'Error: '.(isset($_GET['error'])?$_GET['error']:'')."\n\n";
var_dump($_GET);
}else{
$access_token_response = json_decode(
file_get_contents('https://graph.facebook.com/v2.11/oauth/access_token?'.
'client_id='.$client_id.
'&redirect_uri='.rawurlencode($redirect_url).
'&client_secret='.$client_secret.
'&code='.$_GET['code']
),
true // true means return an associative array
);
if(!$access_token_response || !isset($access_token_response['access_token'])){
print 'Error getting access token: '."\n";
var_dump($access_token_response);
}else{
$profile = json_decode(
file_get_contents('https://graph.facebook.com/v2.3/me?'.
//'fields=id,name,first_name,last_name,age_range,link,gender,locale,picture,updated_time'.
'fields=id,name,first_name,last_name'.
'&access_token='.$access_token_response['access_token']
),
true // true means return an associative array
);
if(!$profile){
print 'Error getting profile';
}else{
print 'name: '.$profile['name']."\n";
print 'id: '.$profile['id']."\n\n";
print 'All:'."\n";
print_r($profile);
}
}
}
}else{
print '<a href="'.
'https://www.facebook.com/v2.11/dialog/oauth?'.
'client_id='.$client_id.
'&redirect_uri='.rawurlencode($redirect_url).
'&response_type=code'.
'&scope=public_profile'.
'" >login with fb</a>';
}
print "\n\n\n\n".'<a href="'.$self_url.'" >start over</a>';
print "\n\n".'</pre></body></html>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment