Google Connect – Google Login System with PHP & MySQL
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.
Live Demo
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”
1 2 3 4 5 6 7 8 |
CREATE DATABASE IF NOT EXISTS login_system; USE login_system; CREATE TABLE IF NOT EXISTS `google_users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; |
I hope you have created a Google app to get CLIENT_ID and CLIENT_SECRET. Set the config.php with all your site and Google related credentials.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// set database credentials define('DB_DRIVER', 'mysql'); define('DB_SERVER', 'localhost'); define('DB_SERVER_USERNAME', 'root'); define('DB_SERVER_PASSWORD', ''); define('DB_DATABASE', 'login_system'); // set site path and redirect URL /* make sure the url end with a trailing slash */ define("SITE_URL", "http://demo.phphive.info/login_system_with_google/"); /* the page where you will be redirected for authorzation */ define("REDIRECT_URL", SITE_URL."login.php"); /* * ***** Google related activities start ** */ define("CLIENT_ID", "Your App CLIENT_ID Here"); define("CLIENT_SECRET", "Your App CLIENT_SECRET Here"); // retreive information from user based on scope/permission define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '. 'https://www.googleapis.com/auth/userinfo.profile' ); /* logout both from Google and your site **/ define("LOGOUT_URL", "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=". urlencode(SITE_URL."logout.php")); |
Set your index.php with the login URL in the anchor tag. So when the user clicks on it it will be redirected to Twitter site.
1 2 3 4 |
<!-- Add login URL in index.php --> <a class="btn btn-block btn-social btn-google-plus" href="login.php"> <i class="fa fa-google-plus"></i> Login with Google </a> |
The page login.php is the main heart of this script. Just setup as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
require('http.php'); require('oauth_client.php'); require('config.php'); $client = new oauth_client_class; // set the offline access only if you need to call an API // when the user is not present and the token may expire $client->offline = FALSE; $client->debug = false; $client->debug_http = true; $client->redirect_uri = REDIRECT_URL; $client->client_id = CLIENT_ID; $application_line = __LINE__; $client->client_secret = CLIENT_SECRET; if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0) die('Please go to Google APIs console page ' . 'http://code.google.com/apis/console in the API access tab, ' . 'create a new client ID, and in the line ' . $application_line . ' set the client_id to Client ID and client_secret with Client Secret. ' . 'The callback URL must be ' . $client->redirect_uri . ' but make sure ' . 'the domain is valid and can be resolved by a public DNS.'); /* API permissions */ $client->scope = SCOPE; if (($success = $client->Initialize())) { if (($success = $client->Process())) { if (strlen($client->authorization_error)) { $client->error = $client->authorization_error; $success = false; } elseif (strlen($client->access_token)) { $success = $client->CallAPI( 'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user); } } $success = $client->Finalize($success); } if ($client->exit) exit; |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
if ($success) { // Now check if user exist with same email ID $sql = "SELECT COUNT(*) AS count from google_users where email = :email_id"; try { $stmt = $DB->prepare($sql); $stmt->bindValue(":email_id", $user->email); $stmt->execute(); $result = $stmt->fetchAll(); if ($result[0]["count"] > 0) { // User Exist $_SESSION["name"] = $user->name; $_SESSION["email"] = $user->email; $_SESSION["new_user"] = "no"; } else { // New user, Insert in database $sql = "INSERT INTO `google_users` (`name`, `email`) VALUES " . "( :name, :email)"; $stmt = $DB->prepare($sql); $stmt->bindValue(":name", $user->name); $stmt->bindValue(":email", $user->email); $stmt->execute(); $result = $stmt->rowCount(); if ($result > 0) { $_SESSION["name"] = $user->name; $_SESSION["email"] = $user->email; $_SESSION["new_user"] = "yes"; $_SESSION["e_msg"] = ""; } } } catch (Exception $ex) { $_SESSION["e_msg"] = $ex->getMessage(); } $_SESSION["user_id"] = $user->id; } else { $_SESSION["e_msg"] = $client->error; } header("location:home.php"); exit; |
and That’s it. Your Google Login System with PHP & MySQL is Ready. 🙂
Live Demo
Hi i have create sign in using google+ through website.but when i click accept after click login by google+ it show the error
Which Error you are Getting ? Please provide Detail info !
hi i have create sign in using google+ But when i click it, i get an error like that
http://www.risingvocalist.com/error.txt
(i do not make a span , so i i upload the text on that link)
I can’t speak english correctly and i don’t know so much about php.
Please do not laugh at me if I made a silly mistake 😀
The login works great with Google, however it lasts for only an hour. How do I refresh the token?
I Downloaded and tested your package. It is working superb. Additionally I need to get profile picture url to integrate in my testimonial page. Please advise how to add the same. In your code ‘name’ for user name and ’email’ for email id. What should i give for profile picture url.
$user->picture will Return User’s Profile Picture Link ( if any )
Excellent buddy, worked like a charm.
How can I make it logout only from the website not from the google account.
Simply destroy_session(); in some Logout.php & Link Logout button to Logout.php
Thanks so much! Works really well!
thankyou so much 🙂
Hi!
Excellent tutorial, works perfectly. However, how can I get users YouTube channel’s url, or the last part of it (id)?
$user->id is something different and not what I’m looking for.
Thanks.
its working fine .
Grate Tutorial………….