Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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');
?>
@ibreakthecloud
Copy link
Author

ibreakthecloud commented Jan 12, 2018

for $code set a different index.php and send your client_id to https://github.com/login/oauth/authorize using GET method with the parameter ?client_id = YOUR-CLIENT-ID

@Rahulmahawar51
Copy link

Rahulmahawar51 commented Jun 13, 2018

Thanks a ton bro..!!

@PlanetTheCloud
Copy link

PlanetTheCloud commented Oct 6, 2018

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

@mieszkoLokietek
Copy link

mieszkoLokietek commented Dec 10, 2018

This is awesome! Thanks!

@Nevercold
Copy link

Nevercold commented Feb 8, 2019

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