Forum Moderators: coopster

Message Too Old, No Replies

PHP Ajax Login System

         

Bengal313

10:08 pm on Mar 1, 2011 (gmt 0)

10+ Year Member



Okay maybe someone can help me out. I been googling and searching everywhere for a login script. I found hundreds but nothing that is easy to install and has these simple features. I have some pages that I want only authorized people to view. So I need to password protect them.

Looking for a script that,
1. When a password protected page is visited the viewer get redirected to a login page, then after authentication, go back to the original page.

2. The login page (form)should have some sort of ajax script so that if you fail a text appears telling to try again and not redirect to an error page.

3. MySQL database used.

Thank you for you help.

CodilX

9:54 am on Mar 2, 2011 (gmt 0)

10+ Year Member



Check every page, if the user has logged in:

if(!$_SESSION['user']) {
header('Location: login.php');
}

For the login itself, I would use jQuery for the ajax part. Let's say you have a login.php:

<?
// if not redirected from a secure page to login form
$_SESSION['redirect'] = $_SERVER['HTTP_REFERER'];
if($_SESSION['user']) { // if user is set and logged in, redirect to previous page
$redirect = $_SESSION['redirect'];
$_SESSION['redirect'] = ''; // unset the redirect session variable
header('Location: '.$redirect);
}
?>

<form id="login">
<input type="text" id="user" />
<input type="password" id="pass" />
<input type="submit" id="submit" />
<span id="error">
</form>

jQuery:
$('#submit').click(function() {
$.post('auth.php?user=' + $('#user').val() + '&pass=' + $('#user').val() + ', function(callback) {
if(callback == 0) {
$('#error').text('Wrong data');
} else {
window.location.reload();
}
});
});

auth.php:
.. check for correct login information etc.
if(everything == ok) {
$_SESSION['user'] = usersomethingwhatver;
echo 1; // everything is ok and logged in
} else {
echo 0; // wrong data enter and show error
}