Publishing System Settings Logout Login Register
AJAX login Using Gmail
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on September 21st, 2008
10995 views
PHP Coding
This tutorial, as you may have guessed, is all about using Gmail as your user database. Now, of course you can't actually fully use their user db, but you can for sure use Gmail for authentication. Safely too no doubt. Here you will be given 2 options, the AJAX version and the non AJAX version. Both do the same thing, just one doesn't reload the page.

This tutorial is intended for people with some knowledge of HTML, JavaScript, and PHP.

Demo Here

Well, here we go. Lets dive right in. Total number of files when finished is 4. Index.php, func.php, proc.js, in.php.

Lets start with index.php. This is of course our index.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX and Gmail Tutorial</title>
<script type="text/javascript" src="inc/proc.js"></script>

</head>

<body>
<p>Gmail Login Demo</p>
<label>

Username
<input type="text" name="username" id="username" />
</label>
<label>
<br />
Password
<input type="password" name="password" id="password" />
</label>
<label> <br />
<input name="button" type="submit" id="button" onclick="login_proc('1')" value="Submit" />
</label>
<p id='response'></p>
</body>
</html>
 


You may notice above certain elements that are of course areas of interest. You may have also noticed no form tag. This page is fairly explanatory so im not going to into to much explanation.

Next we are dealing with the process file proc.js. This of course on does our AJAX and JS.



//GMail Login Tutorial

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); //Not IE
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP"); //IE
    } else {
        //Display your error message here.
        //and inform the user they might want to upgrade
        //their browser.
        alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade to Firefox.");
    }
}

var receiveReq = getXmlHttpRequestObject();

function changeProp(objId,x,theProp,theValue) { //v9.0
  var obj = null; with (document){ if (getElementById)
  obj = getElementById(objId); }
  if (obj){
    if (theValue == true || theValue == false)
      eval("obj.style."+theProp+"="+theValue);
    else eval("obj.style."+theProp+"='"+theValue+"'");
  }
}

function login_proc(act) {
   
  //changeProp('loader','','display','none','DIV');   
   
  var URL="inc/functions.php"; //relative URL


    un = document.getElementById('username').value
    pw = document.getElementById('password').value

   
    params = 'act='+act+'&username='+un+'&password='+pw;
   


    //If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
        //Setup the connection as a GET call
        //True explicity sets the request to asyncronous (default).
        receiveReq.open("POST", URL, true);
       
        receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        receiveReq.setRequestHeader("Content-length", params.length);
        receiveReq.setRequestHeader("Connection", "close");
       
        //Set the function that will be called when the XmlHttpRequest objects state changes.
        receiveReq.onreadystatechange = function() {
        //Check to see if the XmlHttpRequests state is finished.
        if (receiveReq.readyState == 4) {
             //Set the contents of our span element to the result of the asyncronous call.
             if (receiveReq.responseText == 200){
               
                alert ('You have successfully logged in');
                window.location.href('in.php');
               
             } else if (receiveReq.responseText == 401) {
                 alert ('Login FAILED!');
             }
        }
    }
        //Make the actual request.
        receiveReq.send(params);
    }           
}

 


Now, this one ill break it down a bit.

First, we call "login_proc('1')". This will process the initial request and pretty much say "Hey, lets send it off for final say". Next the request is actually sent. Once sent a status code is returned 200 OK or 401 Invalid. We then process that and spit out the message and next command.

Now here is func.php. This will actually do the real work. It will contact the Gmail atom feed and attemp a login with the provided credentials.

<?
session_start();
//functions for server based oporations

    function gLogin ($un, $pw){
   
        $message = '';
        $success = 0;
       
        $credentials['username'] = $un;
        $credentials['password'] = $pw;
       
        if(function_exists('curl_init'))
        {
            if(strlen($credentials['username']) && strlen($credentials['password']))
            {
                $curl = curl_init('https://mail.google.com/mail/feed/atom');
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                //curl_setopt($curl, CURLOPT_HEADER, 1);
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($curl, CURLOPT_USERPWD, $credentials['username'].':'.$credentials['password']);
                $result = curl_exec($curl);
                $code = curl_getinfo ($curl, CURLINFO_HTTP_CODE);

                switch($code)
                {
                    case 200:
                        $_SESSION['logged_in'] = 1;
                         echo 200;
                    break;
                    case 401:
                        echo 401;
                    break;
                    default:
                        $message = 'Result unknown, access denied.';
                        break;
                }
            }
            else  {
               
                echo 'oop';
            }
        }
        else {
            $message = 'curl isn't insalled';
        }
    }
   
    function gLogout () {
   
        //Logout function GLOBAL   
   
        session_start();
        session_unset();
        session_destroy();
   
    }
   
//proccess login
$act = $_REQUEST['act'];

    switch($act)
        {
        case 1: //login
        glogin($_REQUEST['username'], $_REQUEST['password']);
    break;
        case 2: //logout
        glogout();
    break;
        default:
        $message = 'Result unknown, access denied.';
    break;
        }

?>


And that is pretty well self explanatory. But, if you do have any questions, i would be more then happy to answer them. And finally, here is the in.php. Very simple page.

<? 
session_start();
include 'inc/func.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX and Gmail Tutorial</title>
</head>

<body>
<?
if ($_SESSION['logged_in'] == 1){

    echo "if you see this you are logged in. <p><a href='?act=2'>Logout</a></p>";

}else{ ?>
    <script type="text/javascript"> window.location.href = "index.php"; </script>
    <?
}
?>
</body>
</html>
 


Well i thank you for reading and hope you enjoyed the code. Again, if you have any questions please ask.

Generationsix.com
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send


This author is too busy writing tutorials instead of writing a personal profile!
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top