Here is a very basic shell for the code you want. Fill it up with as much stuff as you want but this is the very basics of a MySQL login system.
I have not protected it against any kinds of attacks but if you search around for a minute or two you can find very good resources for protecting your scripts.
I would also recommend recoding my example into OOP, and using PDO for the database work.
login.php
PHP Code
<?php
$errors = array();
include 'functions.php';
if(isset($_POST['submit'])) {
if(userExists($_POST['user'])) {
if(authenticate($_POST['user'], $_POST['pass'])) {
login();
header('Location: private.php');
die();
} else {
$errors[] = 'You have entered an invalid username or password.';
}
} else {
$errors[] = 'That username does not exist.';
}
}
?>
<h1>Login</h1>
<ul>
<?php
foreach($errors as $error) {
echo "<li>{$error}</li>";
}
?>
</ul>
<form action="" method="post">
<input type="text" name="user" />
<input type="password" name="pass" />
<input type="submit" name="submit" value="Login" />
</form>
functions.php
PHP Code
<?php
function authenticate($user, $pass) {
$salt = getSalt($user);
$pass = hashPass($pass, $salt);
$query = mysql_query("SELECT COUNT(id) AS rows FROM users WHERE username = '{$username}' AND password = '{$pass}'");
$row = mysql_fetch_assoc($query);
return ($row['rows'] > 0);
}
function userExists($user) {
$query = mysql_query("SELECT COUNT(id) AS rows FROM users WHERE username = '{$username}'");
$row = mysql_fetch_assoc($query);
return ($row['rows'] > 0);
}
function getSalt($user) {
$query = mysql_query("SELECT salt FROM users WHERE username = '{$username}'");
$row = mysql_fetch_assoc($query);
return $row['salt'];
}
function hashPass($pass, $salt) {
return hash('sha512', $pass . $salt);
}
function login() {
$_SESSION['loggedin'] = true;
}
function logout() {
$_SESSION['loggedin'] = false;
}
function loggedIn() {
return (!empty($_SESSION['loggedin']) && $_SESSION['loggedin'] === true);
}
?>
private.php
PHP Code
<?php
if(!loggedIn()) {
header('Location: login.php');
die();
}
?>
private stuff
database structure
Code
name: users
id - username - password