Login script in PHP/MySQL
A simple login script using PHP and MySQL. It’s safe against SQL injections and uses sha1 encryption for the passwords.
login.php
<?php
session_start();function salt($pw) {
$salt = “This comment should suffice as salt.”;
return sha1($salt.$pw);
}if (isset($_POST['submit'])) {
mysql_connect(“localhost”, “root”, “”) or die(“Cannot open connection: ” . mysql_error());
mysql_select_db(“experiment”) or die(“Database not found”);$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password = salt($password);$query = mysql_query(“SELECT * FROM loginscript WHERE username=’$username’ AND password=’$password’”);
if (mysql_num_rows($query) == 0) {
header(“location: index.php”);
exit;
}$_SESSION['user'] = $username;
header(“location: index.php”);
}
?>
index.php
<?php
session_start();if (isset($_GET['logout'])) {
session_unset();
session_destroy();
header(“location: index.php”);
exit;
}
?>
<html>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=iso-8859-1″>
<title>Login Script</title>
<style type=”text/css”>
body { font-size: 12px; }
input { font-size: 12px; }
</style>
</head><body>
<?php
if (isset($_SESSION['user'])) {
echo “You are logged in!”;
echo “<br><a href=’?logout’>Log out</a>”;
} else {
?><h2>Member Login</h2>
<form action=”login.php” method=”POST”>
Username:<br>
<input type=”text” name=”username”><br>
Password:<br>
<input type=”password” name=”password”><br>
<input type=”submit” name=”submit” value=”Login”>
</form><?php
}
?></body>
</html>