Skip to content

Instantly share code, notes, and snippets.

@ibreakthecloud
Last active December 16, 2019 14:51
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ibreakthecloud/ce6aa436cecf5388c5c6d275a3d5c108 to your computer and use it in GitHub Desktop.
Complete PHP 7 code for Implementing OAuth via Github
<?php
session_start();
$code = $_GET['code'];
$url = 'https://github.com/login/oauth/access_token';
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// echo $code;
$postdata = http_build_query(
array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'code' => $code
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$json_url = 'https://api.github.com/user?'.$result;
$options = array('http' => array('user_agent'=> $_SERVER['HTTP_USER_AGENT']));
$context = stream_context_create($options);
$response = file_get_contents($json_url, false, $context);
$response = json_decode($response);
print_r($response->login);
print_r('<img border = "10px" src="'.$response->avatar_url.'"><br>');
echo "Hello<br>";
print_r($response->name);
$_SESSION['name'] = $response->name;
$_SESSION['imgURL'] = $response->avatar_url;
$_SESSION['username'] = $response->login;
$_SESSION['logged_in'] = '1';
//Enable the following to redirect to another page
// header('location:chat.php');
?>
@Rahulmahawar51
Copy link

Thanks a ton bro..!!

@PlanetTheCloud
Copy link

I received a 404 error when cURL-ing https://github.com/login/oauth/access_token...

@mieszkoLokietek
Copy link

This is awesome! Thanks!

@Nevercold
Copy link

What should I specify for the code variable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment