I use the following user authentication script I have developed. Do you think it's secure?
// index.php:
// *****************
<?php
if ((isset($_POST['username'])) && (isset($_POST['password']))) {
// *** Check username and password
$username = $_POST['username'];
$password = $_POST['password'];
// *** Connect to the MySql database (not in public_html)
require("../../connect.php");
$sql = "select * from users_table where username='$username' and password=password('$password')";
$result = mysql_query($sql,$con);
if (mysql_num_rows($result) == 1) {
$session_id = md5(uniqid(rand()));
$timestamp = time();
setcookie("username","$username",time()+14400,"/","",0);
setcookie("session_id","$session_id",time()+14400,"/","",0);
$sql = "update users_table set session_id='$session_id', session_timestamp='$timestamp' where username='$username'";
$result = mysql_query($sql,$con) or die ("A problem occurred");
header("Location: secure_site.php");
exit;
}
}
?>
<html>
<head>
<title>Log In</title>
</head>
<body>
<form action="<?php echo $PHP_SELF; ?>" method="post">
<table border="0" bgcolor="#000030" cellspacing="0" cellpadding="1" width="320">
<tr><td>
<table border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#F9F9F9">
<tr><td align="center">
<table border="0" cellpadding="0" cellspacing="3" width="100%" bgcolor="#F9F9F9" align="center">
<td colspan="2" align="center">
<br><b>Please enter your username and password:</b>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table border="0" cellpadding="0" cellspacing="10" width="200" bgcolor="#F9F9F9">
<tr>
<td width="90">Username:</td>
<td><input type="text" maxlength="20" name="username" size="15"></td>
</tr>
<tr>
<td width="90">Password:</td>
<td><input type="password" maxlength="20" name="password" size="15"></td>
</tr>
<tr>
<td align="right" colspan="2"><input type="submit" value="Log In">
</tr>
</table>
</td>
</table>
</td></tr>
</table>
</td></tr>
</table>
</form>
</center>
</body>
</html>
// *** End of index.php
check_user.php is require()d in the beginning of every page to be secured:
// check_user.php:
// *******************
<?php
if ((!isset($_COOKIE['username'])) || (!isset($_COOKIE['session_id']))) {
header("Location: index.php"); // Redirect to the login page
exit;
}
else {
$username = $_COOKIE['username'];
$session_id = $_COOKIE['session_id'];
$min_session_timestamp = time() - 14400; // session_id is only valid for 14400 seconds (4 hours), like the cookie
$sql = "select username from users_table where username='$username' and session_id='$session_id' and session_timestamp>=$min_session_timestamp";
$result = mysql_query($sql,$con);
if ((mysql_num_rows($result)) != 1) {
header("Location: index.php"); // Redirect to the login page
exit;
}
}
?>
// *** End of check_user.php
What do you think? Can this script be hacked and if so, how? Thanks.