Skip to content

Instantly share code, notes, and snippets.

@krishagel
Last active December 10, 2015 09:58
Show Gist options
  • Save krishagel/4417308 to your computer and use it in GitHub Desktop.
Save krishagel/4417308 to your computer and use it in GitHub Desktop.
PHP page to authenticate using oauth and pull information about a users with the Github API.
<?php
$randint = mt_rand();
$client_id = '<app ID goes here>';
$client_secret = '<app secret goes here>';
if ($_GET['code']) {
$code = $_GET['code'];
$state = $_GET['state'];
$url = 'https://github.com/login/oauth/access_token';
$vars = 'client_id=' . $client_id . '&client_secret=' . $client_secret . '&code=' . $code . '&state=' . $state;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
curl_close($ch);
parse_str($response,$output);
$token = $output['access_token'];
$ch = curl_init();
$options = array(CURLOPT_URL => 'https://api.github.com/user?access_token=' . $token,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
$user = json_decode(curl_exec($ch));
curl_close($ch);
echo $output['access_token'] . '<br />';
echo $user->login . '<br />';
echo $user->email . '<br />';
echo $user->location . '<br />';
} else {
echo 'Start Over';
}
?>
<a href="https://github.com/login/oauth/authorize?client_id=5ff0b1ffdc460dcc4eab&state=<?php echo $randint;?>">Login</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment