In this tutorial you will see how to make a Login System with Google using php and mysql. User will login with their Google account, give permission to access basic profile, and their name with email will be stored in database if they are not stored before.
How to Create a Google OAuth Application for Website Login
In case if you are a newbie, Watch the following Video before proceeding.
How login with Google works?
Here’s how this script is going to work.
You will have to create a project in Google to get CLIENT ID and SECRET KEY. without that it will not work.
After you are done with Step 1 , you will go to the website say “http://demo.phphive.info/login_system_with_google/index.php” where you will click on login with google button.
It will redirect you to google_login.php which will again redirect to go Google Site, where you will have to login with your google account and then allow the permission to the project. It will redirect you back to your google_login.php
If there is any error, it will send you back to index.php, or if everything is perfect it will check the database for existing email ID. If email ID does not exist it will save it with your name and email ID. and redirect to home.php. If email ID is already present in the database it will just redirect to home.php with welcome message.
Steps to Create Google Login System with PHP and MySQL
Lets Code Now, Create a Database named “login_system” or Anything and Create a Table “google_users”
The above code is just the basic code for authenticating user. Either it will give user details on success or error on failure based on that you have to code the database part and final redirection. If it returns error redirect back to index.php. If api returns user details check with database if user email exist and do the necessary accordingly and redirect back to home.php
// Now check if user exist with same email ID
$sql="SELECT COUNT(*) AS count from google_users where email = :email_id";
// User Exist
// New user, Insert in database
$sql="INSERT INTO `google_users` (`name`, `email`) VALUES "."( :name, :email)";
and That’s it. Your Google Login System with PHP & MySQL is Ready. 🙂