PHP - Login System

From Global Programming Syntax

Jump to: navigation, search

When you have a login system, you will need to use some sort of data storage to keep track of the usernames and passwords. Generally the best solution is a database (eg. MySQL). The below example uses MySQL you need to setup a database with a table named 'users' and two columns named 'username' and 'password'. So the first script is the page named 'login.php'.

<? session_start();
$dbhost='localhost'; //database host (usually localhost)
$accountname='root'; //database username.
$password=''; //database password
$database='my_database'; //database name - not table
//configure the above variables.
 
 
$linkID = @mysql_connect($dbhost,$accountname,$password)
or die("Could not connect to MySQL server");
@mysql_select_db($database) or die("Could not select database");
 
//adjust mysql query accordingly
$result=mysql_query("SELECT * FROM `users` WHERE `username`='".
mysql_real_escape_string($_POST['username'])."' AND `password`='".mysql_real_escape_string($_POST['password'])."'");
 
if (isset($_POST['username']) && mysql_num_rows($result)==1)
{
$row=mysql_fetch_array($result);
$_SESSION['username111']==$row['username'];
unset($row);
header('Location: index.php');
//there should be no browser output before this line.
}
?>
<form method='post'>
<input type='text' value='Admin' name='username'><br>
<input type='text' value='password' name='password'>
<input type='submit' value='submit'>
</form>


Then the following will be placed at the top of index.php so when you visit "index.php", you need to be logged in and can view new content otherwise you will just view an error message.

<?
session_start();
if (!isset($_SESSION['username111']))
{
echo "You are not logged in ";
//if not logged in this will occure.
} else {
//if logged in this will occure.
echo "This is password protected content ".$_SESSION['username111'];
}
Personal tools
languages
page stats
Toolbox