Login with GitHub OAuth in PHP
GitHub is a version control platform used for team collaboration. It is primarily used by developers to maintain source code in an efficient manner. Learn in this article how to implement login with GitHub in a PHP application.

GitHub offers OAuth app creation, which is used as an authentication provider service. With the GitHub OAuth app, it is possible to allow visitors to log in to a web application using their GitHub account. In this post we, will add a GitHub login button in PHP and allow users to authenticate using their GitHub account. Files for GitHub login interface will be:
- constants.php: A constants file for GitHub credentials.
- index.php: A PHP file with HTML content for a button and displaying authenticated user details.
- github-oauth-client.php: A PHP class to make requests to GitHub OAuth.
- logout.php: A PHP file to log out authenticated users.
- style.css: The stylesheets for the GitHub login interface.
How to Integrate GitHub OAuth Login in PHP
Implementing third-party login providers like login with Google and login with Microsoft account enhances the user experience of a web application. With a few simple steps, we can also authenticate users with a GitHub OAuth app in a PHP application. First, we need to create an OAuth app in GitHub, generate a client ID and client secret, and then write some code to build a secure login system where users can log in using their GitHub account. Steps to log in with GitHub in PHP are as follows:
Step 1: Create an OAuth App in GitHub
In order to allow website users to log in with a GitHub account, we first need to create an OAuth app in GitHub and get the client ID and client secret to use in our PHP application.
- Log in to your GitHub account.
- Click on your avatar in the top right header section and click "Settings".
- On the settings screen, click "Developer Settings" in the left side navigation menu.
- On the developer settings page, click "OAuth Apps" in the left navigation menu.

- On the OAuth Apps page, click "New OAuth App".
- Enter a name for the application, homepage URL and authorization fallback URL in the fields.

- After filling out all required fields, click "Register Application".
- After registering the application, click on "Generate new client secret" on the OAuth app page.
Step 2: Configure GitHub Client ID & Client Credentials (OAuth App Credentials)
We will need the client ID and client secret from GitHub app credentials to securely make API requests to GitHub. We save these credentials in a PHP constants file.
constants.php
<?php
define('BASE_URL', 'https://' . filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL) . '/');
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
Step 3: Create a PHP Class to Authenticate Users with GitHub OAuth
We create a PHP class, github-oauth-client.php to send API requests to the GitHub OAuth application. The class will contain two methods: get_access_token() to fetch an access token from GitHub and get_authenticated_user() to get details of the authenticated user. There is also a private function curl_request(), which is used by these two methods.
- Set private class properties
$client_idand$client_secretto be used in our class methods. - Add a method
get_access_token()to get an access token from theGitHub OAuth app for a provided OAuth code. - Add a method
get_authenticated_user()to fetch data for an authenticated user from GitHub the OAuth app. - Add a private method
curl_request()to handle API requests sent to GitHub endpoints and return the response.
github-oauth-client.php
<?php
class github_oauth_client
{
private string $client_id;
private string $client_secret;
public function __construct($client_id, $client_secret)
{
$this->client_id = $client_id;
$this->client_secret = $client_secret;
}
/**
* @param string $oauth_code
* @return mixed
* @throws Exception
*/
public function get_access_token(string $oauth_code): mixed
{
$api_url = sprintf('https://github.com/login/oauth/access_token?%s', http_build_query([
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'code' => $oauth_code,
]));
$response = json_decode($this->curl_request($api_url, 'GET'));
return $response->access_token;
}
/**
* @param string $access_token
* @return mixed
* @throws Exception
*/
public function get_authenticated_user(string $access_token): mixed
{
$api_url = 'https://api.github.com/user';
return json_decode($this->curl_request($api_url, 'GET',
[
'Authorization' => sprintf('token %s', $access_token),
],
[
CURLOPT_USERAGENT => 'CodeStacked Login'
]
));
}
/**
* @param string $url
* @param string $method
* @param array $headers
* @param array $curl_options
* @return bool|string
* @throws Exception
*/
private function curl_request(string $url, string $method = 'GET', array $headers = [], array $curl_options = []): bool|string
{
$curl = curl_init();
array_change_key_case($headers);
$headers = array_merge(['accept' => 'application/json'], $headers);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if (str_starts_with($url, 'https://')) {
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
}
// If any headers set add them to curl request
if (!empty($headers)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($headers), array_values($headers)));
}
// Set the request type , GET, POST, PUT or DELETE
switch (strtoupper($method)) {
case 'POST':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
break;
case 'PUT':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
break;
}
// Any extra curl options to add in curl object
if (!empty($curl_options)) {
foreach ($curl_options as $option_key => $option_value) {
curl_setopt($curl, $option_key, $option_value);
}
}
$response = curl_exec($curl);
$error = curl_error($curl);
$error_code = curl_errno($curl);
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($error_code > 0) {
throw new Exception($error, $error_code);
}
if ($status_code !== 200) {
throw new Exception($response, $status_code);
}
curl_close($curl);
return $response;
}
}
Step 4: Create a Login with GitHub Button (PHP)
We also need a user interface where users can log in with a GitHub account. This interface renders a login with GitHub button. When this button is clicked, the user will be redirected to the authentication page. On the authentication page, the user allows the web application to access basic account data and is redirected back to the web application. This interface will show the details of the authenticated user if the user has already signed in.
- At the top of the index page, start a session if it is not already started.
- Include the constants file and GitHub client file.
- Create an instance
$github_oauth_clientproviding the client ID, client secret and fallback URL. - Check if there is already an access token set in the session, then fetch the authenticated user details from GitHub.
- Check if there is a "code" query parameter set in the URL, which indicates the user returned from the authorization page of GitHub. Get the access token from GitHub for the given OAuth code and redirect the user to the same page.
- In the HTML section of the page, check if the access token is set in the session, then the user details are already fetched and displayed.
- If the access token is not set, then display the login with GitHub button.
index.php
<?php
if (!session_id()) {
session_start();
}
include_once 'constants.php';
include_once 'github-oauth-client.php';
$github_oauth_client = new github_oauth_client(CLIENT_ID, CLIENT_SECRET);
if (isset($_SESSION['access_token'])) {
$user_info = $github_oauth_client->get_authenticated_user($_SESSION['access_token']);
/**
* YOU CAN STORE USER INFORMATION TO DATABASE HERE
*/
}
$code = filter_input(INPUT_GET, 'code');
if (!empty($code)) {
$access_token = $github_oauth_client->get_access_token($code);
$_SESSION['access_token'] = $access_token;
header('location: ' . BASE_URL . 'login-with-github-oauth-in-php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login with GitHub OAuth in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<?php if (isset($_SESSION['access_token'])) { ?>
<h3>You are logged in as:</h3>
<div class="user-details-container">
<div class="github-avatar-container">
<img src="<?= $user_info->avatar_url; ?>"
class="github-avatar"
width="100" height="100" alt=""/>
</div>
<div class="user-details">
<div>
<label>OAuth ID:</label>
<span><?= $user_info->node_id; ?></span>
</div>
<div>
<label>Name:</label>
<span><?= $user_info->name; ?></span>
</div>
<div>
<label>Profile URL:</label>
<span><a href="<?= $user_info->html_url; ?>" rel="nofollow" target="_blank">Profile</a></span>
</div>
<div>
<a href="logout.php" rel="nofollow">Logout</a>
</div>
</div>
</div>
<?php } else { ?>
<a href="<?= sprintf('https://github.com/login/oauth/authorize?%s', http_build_query([
'client_id' => CLIENT_ID,
'redirect_uri' => BASE_URL . 'login-with-github-oauth-in-php',
'scope' => 'read:user user:email',
])); ?>" class="btn-github">
<svg width="25" height="25" aria-hidden="true" viewBox="0 0 24 24" data-view-component="true"
fill="#ffffff">
<path d="M12 1C5.9225 1 1 5.9225 1 12C1 16.8675 4.14875 20.9787 8.52125 22.4362C9.07125 22.5325 9.2775 22.2025 9.2775 21.9137C9.2775 21.6525 9.26375 20.7862 9.26375 19.865C6.5 20.3737 5.785 19.1912 5.565 18.5725C5.44125 18.2562 4.905 17.28 4.4375 17.0187C4.0525 16.8125 3.5025 16.3037 4.42375 16.29C5.29 16.2762 5.90875 17.0875 6.115 17.4175C7.105 19.0812 8.68625 18.6137 9.31875 18.325C9.415 17.61 9.70375 17.1287 10.02 16.8537C7.5725 16.5787 5.015 15.63 5.015 11.4225C5.015 10.2262 5.44125 9.23625 6.1425 8.46625C6.0325 8.19125 5.6475 7.06375 6.2525 5.55125C6.2525 5.55125 7.17375 5.2625 9.2775 6.67875C10.1575 6.43125 11.0925 6.3075 12.0275 6.3075C12.9625 6.3075 13.8975 6.43125 14.7775 6.67875C16.8813 5.24875 17.8025 5.55125 17.8025 5.55125C18.4075 7.06375 18.0225 8.19125 17.9125 8.46625C18.6138 9.23625 19.04 10.2125 19.04 11.4225C19.04 15.6437 16.4688 16.5787 14.0213 16.8537C14.42 17.1975 14.7638 17.8575 14.7638 18.8887C14.7638 20.36 14.75 21.5425 14.75 21.9137C14.75 22.2025 14.9563 22.5462 15.5063 22.4362C19.8513 20.9787 23 16.8537 23 12C23 5.9225 18.0775 1 12 1Z"></path>
</svg>
<span>Login with GitHub</span>
</a>
<?php } ?>
</div>
</section>
</body>
</html>
Step 5: Log Out of GitHub in PHP
We also need an interface that allows users to logout from application. So we create a PHP logout file, which will unset the access token set in the session and redirect the user to the index or login page.
logout.php
<?php
if (!session_id()) {
session_start();
}
include_once 'constants.php';
unset($_SESSION['access_token']);
header('Location:' . BASE_URL . 'login-with-github-oauth-in-php');
Step 6: Add CSS Styles for GitHub Login Page
Add necessary CSS styles for our index page, which contains the GitHub login button and user details for authenticated users.
style.css
* {
box-sizing: border-box;
text-decoration: none;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
line-height: 1.5;
}
.container {
width: 100%;
max-width: 1140px;
margin-right: auto;
margin-left: auto;
padding-right: 15px;
padding-left: 15px;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.user-details-container {
background-color: #ffffff;
border: 1px solid #dddddd;
display: inline-flex;
gap: 1rem;
padding: 1rem;
}
.github-avatar-container {
overflow: hidden;
width: 100px;
height: 100px;
}
.github-avatar {
max-width: 100%;
height: auto;
display: inline-block;
border-radius: 100%;
}
.btn-github {
display: inline-block;
background-color: #1f2328;
color: #ffffff;
border: 1px solid #1f2328;
padding: 0.5rem 1rem;
}
.btn-github svg {
vertical-align: middle;
}
.btn-github span {
display: inline-block;
margin-left: 1rem;
}By following this step-by-step guide, we are now able to implement GitHub OAuth Login in PHP efficiently. Integrating login with GitHub improves user experience and also enhances security by following OAuth 2.0 standards. The implementation can be extended by storing the user information in a database.