Secure login form with AJAX, Javascript + PHP
Hello, It has been quite a while since I posted a tutorial on this website and I have noticed that my Javascript/AJAX tutorials are in quite high demand. In between developing some other sites, I remembered how interesting it was coding my admin panel's secure AJAX login and how little documentation there was about such a method on the internet.
[b]The theory[/b]
The page I was protecting was to be accessed by me only and was to display a login prompt to all users attempting to access it. The form would then be filled in and the data would be sent to my PHP script. The PHP script would then need to decide wether or not the user's credentials are correct and either display the page requested or refuse the user access. The problem that I faced was that it was very difficult to create a javascript function that would do all this while remaining secure. I think my method is hack-proof but I will soon find out when this source code is read by the public, so here goes!
[b]How it's done[/b]
The first thing we will need is a HTML login form, but not a normal login form. This one will contain an [i]onSubmit[/i] attribute containing our javascript function call. Here is the form we will be using:
[code]<div id="content">
<form action="javascript:void(0);" onsubmit="login(document.getElementById('user').value,document.getElementById('pass').value);">
<p>
Username<br /><input id="user" type="text" /><br />
Password<br /><input id="pass" type="password" />
<input id="submitpop" type="submit" value="" />
</p>
</form>
</div>
[/code]
The action attribute is set to call [i]javascript:void(0);[/i] which simply ensures that the form does not post the data conventionally. The onSubmit attibute calls our javascript function, which will be used to authorise the user. We use [i]document.getElementById('input_id').value[/i] to send the values of the user and pass text inputs to our javascript.
Next, we need to create the javascript function [i]login[/i].
[code]function createhandler(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
return xmlhttp;
}
function login(user,pass)
{
var content=document.getElementById('content');
var xmlhttp=createhandler();
var params='user='+user+'&pass='+pass;
xmlhttp.open('POST', '/login.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('Content-length', params.length);
xmlhttp.setRequestHeader('Connection', 'close');
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4){
if(xmlhttp.responseText!=0)
{
xmlhttp.open('POST', '/loggedin.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('Content-length', params.length);
xmlhttp.setRequestHeader('Connection', 'close');
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML=xmlhttp.responseText;
}
};
xmlhttp.send(params);
}
else
{
alert("Failled Login");
}
}
};
xmlhttp.send(params);
}[/code]
The [i]login[/i] function starts by calling [i]createhandler[/i]. This returns our ajax [i]XmlHttpRequest[/i] object. The function then posts our username and password to login.php. If login.php returns a value other than '0' then loggedin.php is loaded with the same user and password as login.php, this extra step probably isn't really necessary but it was the way I coded the function for my purpose. It may be just as easy to put your content inside login.php, but for some reason I didn't. If 0 is returned, then an alert box is called with the text "Failled Login" and no further action is taken.
That is it for the HTML and Javascript. The next step is our php file(s) which determine wether or not a correct username + password has been entered. For my script I used a username and password stored in a MySQL database but for ours we are going to set the correct values within the script.
[b]login.php[/b]
[php]
$user=’username’; //Our username
$pass=’password’; //Our password
if($user==$_POST['user'] && $pass==$_POST['pass'])
echo 1;
else
echo ‘Failled Login’;
?>[/php]
This PHP script checks if the username submitted is [i]username[/i] and the password is [i]password[/i]. If the combination is correct, it displays 1, 0 if it is incorrect.
[b]loggedin.php[/b]
[php]
$user=’username’; //Our username
$pass=’password’; //Our password
if($user!=$_POST['user'] || $pass!=$_POST['pass'])
return;
echo’Anything below the return; statement will be displayed only if the correct password is entered. There is no need for an error message as this page should only be accessed by a javascript hack attempt or correct password
’;
?>[/php]
The page will return blank if it is not given the correct username and password. If it is, the page is displayed. If you want a user to be logged in without having to enter his details again, it is a good idea to store his username + password in a session or cookie. If you are reading this tutorial though, I would assume you already know how to do this. If you want information about how to implement sessions or cookies into this script, please leave a comment below and I will write another tutorial.
Peace
Stephen
[b]PS.[/b] I would love for someone to try to hack the system on this site so please do, this code is implemented as written on my admin login available if you right-click. I would love to hear any weaknesses the code has so feel free to try