26 March, 2013

PHP MySQL login page


Now lets create a login page
First we create a login form and name it "login.php" and using post as a method
<form action="checkLogin.php" method="post">
<table border="0">
<tr>
<td colspan=2><h1>Login</h1></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="username" maxlength="40"></td>
</tr>
<tr>
<td>Password:</td>
<td> <input type="password" name="password" maxlength="50"></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" name="login" value="Login"></td>
</tr>
</table>
</form>


We'll use the same database table from the last post "member" table.

Create a new page and name it "checkLogin.php" where we'll check the username and password


<?php

// check if all fields are filled up

if (isset($_POST['login'])) { 
  if(!$_POST['username'] | !$_POST['password']) {
  echo "You did not fill in a required field";
include("login.php");
exit;
  }

        // Check if user exists 

$query = mysql_query("SELECT * FROM member WHERE username = '".$_POST['username']."'")or die(mysql_error());
$sql = mysql_num_rows($query);
if ($sql == 0) {
echo('That user does not exist in our database.');
}
while($info = mysql_fetch_array($query)) {
$_POST['password'] = stripslashes($_POST['password']);
$info['password'] = stripslashes($info['password']);
 
if ($_POST['password'] != $info['password']) {
header('Location: login.php');
} else {
$_POST['username'] = stripslashes($_POST['username']);
                        // set cookie for 24 hours
$hour = time() + 86400;
setcookie(username, $_POST['username'], $hour);
setcookie(password, $_POST['password'], $hour);
}
}
}
?> 


No comments:

Post a Comment