How to create a Log in with GitHub button for users to log in on your website in PHP
Creating a "Login with GitHub" button involves creating a GitHub application, adding a button to your website, handling the authorization callback URL, and exchanging the authorization code for an access token.
To create a “Login with Github” button for users to log in with their GitHub account on your website, you can follow these steps:
Step 1
First, you need to create a GitHub application. Go to GitHub and fill in the required fields. You will need to provide a name for your application, the homepage URL of your website, and the authorization callback URL. The authorization callback URL is the URL that GitHub will redirect the user to after they have authorized your application. This URL must be on your website domain.
Step 2
After creating your GitHub application, you will be provided with a Client ID and a Client Secret. Keep these credentials safe as you will need them in the next step.
Step 3
Next, you will need to add a “Login with Github” button to your website. You can use the GitHub logo or any other design of your choice for the button. When the user clicks on this button, it should redirect them to the GitHub OAuth authorization page.
<?php
$github = new ProjectsEngine\Github();
$githubURL = $github->get_authorize_url('github' );
?>
<a alt="github" class="github" href="<?= $githubURL; ?>" target="_blank" title="Github">
<span class="text">Github</span>
</a>
Let’s add all of our code in one simple class.
<?php
namespace ProjectsEngine;
class Github
{
private $clientID;
private $clientSecret;
private $redirectUri;
private $apiURLBase;
private $authorizeURL;
private $tokenURL;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
*/
public function __construct()
{
$this->clientID = '';
$this->clientSecret = '';
$this->redirectUri = site_url() . '/verify/';
$this->apiURLBase = 'https://github.com/login/oauth/';
$this->authorizeURL = $this->apiURLBase . 'authorize';
$this->tokenURL = $this->apiURLBase . 'access_token';
}
/**
* Get to authorize URL
*
* @param $state
*
* @return string
*/
public function get_authorize_url($state)
{
return $this->authorizeURL . '?' . http_build_query([
'client_id' => $this->clientID,
'redirect_uri' => $this->redirectUri,
'state' => $state,
'scope' => 'user, read:user, user:email, user:follow'
]);
}
}
Step 4
In the authorization URL, you will need to include the Client ID and the authorization scope. The authorization scope specifies the permissions that your application will have when it accesses the user’s GitHub account. For example, if you want to access the user’s email address, you will need to include the “user:emai
l” scope. You can include multiple scopes by separating them with commas.
Step 5
After the user authorizes your application, Github will redirect them to the authorization callback URL that you specified in step 1. This URL should handle the authorization code that Github provides in the query string. You can exchange this code for an access token by making a POST request to the GitHub API.
/**
* Get the access token
*
* @param $code
*
* @return mixed
*/
public function get_access_token($code) {
$parameters = http_build_query([
'client_id' => $this->clientID,
'client_secret' => $this->clientSecret,
'code' => $code,
'redirect_uri' => $this->redirectUri,
]);
// Set up cURL
$ch = curl_init();
// Set the URL and parameters for the access token request
curl_setopt($ch, CURLOPT_URL, $this->tokenURL );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters );
// Set the headers for the access token request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
));
// Get the response from the access token request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
// Check if the request was successful
if( $info['http_code'] == 200 ) {
// Access token received, handle the response
$json = json_decode($response, true);
// Close the cURL session
curl_close($ch);
return $response && isset( $json['access_token'] ) ? $json['access_token'] : false;
}
// Access token request failed, handle the error
return false;
}
Step 6
Once you have the access token, you can use it to make API requests to GitHub on behalf of the user. For example, you can use the access token to fetch the user’s profile information, repositories, and other data.
/**
* Get user emails.
* @api https://api.github.com/user
*
* @param $token
* @return mixed
* @since 1.0.0
*/
public function get_user_emails( $token ) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/user/emails');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Accept: application/vnd.github+json';
$headers[] = 'Authorization: Bearer '. $token;
$headers[] = 'X-Github-Api-Version: 2022-11-28';
$headers[] = 'User-Agent: Projects Engine';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return json_decode( $result , true );
}
/**
* Get user.
*
* @param $token
* @return mixed
*/
public function get_user( $token ) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/user');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Accept: application/vnd.github+json';
$headers[] = 'Authorization: Bearer '. $token;
$headers[] = 'X-Github-Api-Version: 2022-11-28';
$headers[] = 'User-Agent: Projects Engine';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return json_decode( $result , true );
}
Overall, creating a “Login with GitHub” button involves creating a GitHub application, adding a button to your website, handling the authorization callback URL, and exchanging the authorization code for an access token.