HW2: Jess Tait, Rachel Foecking, Sarah Thayer


Sthayer (Talk | contribs)
(2 files for login script HW)
Newer edit →

Revision as of 17:27, 1 October 2009

index.html: user logs in with username and password

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

checklogin.php: connects to server, database, ensures username and password are correct, logs user in, puts timestamp into user's last_login field.


<?php
ob_start(); //start output buffer
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="login"; // Database name
$tbl_name="users"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

// encrypt password
$encrypted_mypassword=md5($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row; therefore it is correct user

if($count==1){
// Register $myusername, $mypassword
session_register("myusername");
session_register("mypassword");

echo "Login successful. Welcome $myusername.";

//put current timestamp into users table for last_login field
$sql="UPDATE ".users." SET last_login=CURRENT_TIMESTAMP WHERE ".username."='$myusername'";
mysql_query($sql);
}

else {
//if the username and password do not match, return user to login screen
echo "Wrong Username or Password";
header("location:index.html");
}
ob_end_flush();
?>