<?php
/* This page checks user information and
* logs them in if it's correct.
*
* First, we need to check if the form has
* been submitted. If it has, we need to check
* form values, to make sure they filled them in
* right.
*
* Connect to MySQL and check if the form has
* been submitted:
*/
// Connect to MySQL. Change the values to your information:
$mysql = mysqli_connect
('localhost', 'username', 'password', 'database') or
die('An error has occured.'); // Check if the form has been submitted:
if(isset($_POST['username']) && isset($_POST['passsword'])) { // Now we check that both forms were filled in:
if(!empty($_POST['username']) && isset($_POST['password'])) { // We're all good, so we can assign the post values to variables:
/* Now we can refer to $_POST['username'] as
* $username. It's much faster and easier. We
* user extract() because it's easier than
* doing it manually. Caution: May make you lazy
* :P
*
* Now we can query our database for the username
* and password combonation. If it returns no rows
* with the inputted password AND username, either
* the password does not match the username, or the
* user inputted information that does not exist.
*
* We can assign the user id to a session, and use
* that to retrieve all the information about the
* user from the table.
*/
if($query = $mysql->prepare('SELECT userid FROM users WHERE username = ? AND
password = ?')) {
$query->bind_param('ss', $username, $password);
$query->execute();
$query->store_result();
/* Now we count the number of rows returned. As
* I stated before, if the number of rows is less
* than one, the user has failed to input valid
* information.
*/
if($query->num_rows < 1) {
// Login unsuccessful. Echo error:
echo('Incorrect information provided. Login failed.'); } else {
/* The login was successful! We need to assign the user
* id to a session for later use (retrieving information,
* etc). First however, we need to retrieve the user id:
*/
$query->bind_result($userid);
if($query->fetch()) {
// Assign the user id to a session:
$_SESSION['userid'] = $userid;
// Redirect user to the logged in page:
header('Location: loggedin.php'); }
}
} else {
// The query failed to be prepared:
die('An error has occured.'); }
}
}
?>
<!-- Login Form -->
<form action="login.php"
method="post">
<fieldset>
<legend>Login To Your Account</legend>
<label for="username">Username:</label> <input type="text" id="username" name="username" /><br />
<label for="password">Password:</label> <input type="password" id="password" name="password" /><br />
<input type="submit"
name="submit" value="Login" />
</fieldset>
</form>