Intro to PHP – Creating a Basic Login System

Using a little knowledge of PHP and HTML you can build a simple log in system for your site. In order to correctly follow this tutorial you may want to have a good idea of basic HTML/PHP syntax as well as knowing some CSS. You should also have a basic understanding of how to create and use sessions($_SESSIONS) in PHP.

Alright let’s get started by just creating a basic log in window and place it in the center of the screen. First the log in window.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<div id="outerLimit">
			<div id="container">
				<div id="innerLimit">
					<div id="loginBox">
						<form id="login" name="login" method="post" action="userAuth.php">
							<label for="username">Username:</label><br />
							<input type="text" id="username" name="username" size=40 /><br />
							<label for="password">Password:</label><br />
							<input type="password" id="password" name="password" size=40 /><br />
 
							<input type="submit" name="submit" value="Log In" />
						</form>
						<br />
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

Next let’s move into a bit of the CSS. Basically we just want to create a window with a gray background so the fields are extremely easy to see. I called the CSS file in this case loginCSS.css but you can call it whatever you like as long as it’s referenced properly in the HTML section.

body
{
	background-color:white;
	min-height: 468px;
	min-width:552px;
	font-family:Helvetica;
}
 
a
{
	font-size:small;
}
 
#loginBox
{
	background-color: #e4e4e4;
	position:relative;
	top:25%;
	left:25%;
	width:300px;
	padding:15px;
}
 
#outerLimit
{
	height:100%;
	width:100%;
	display:table;
	vertical-align:middle;
}
 
#container
{
	position:relative;
	vertical-align:middle;
	display:table-cell;
	height:468px;
}
 
#innerLimit
{
	width:552px;
	height:468px;
	margin-left:auto;
	margin-right:auto;
}

As you can see, I just styled the page a little bit to make it a little bit easier for the user to use. Now that we have a basic page for the user to log in, we’ll also need a page, such as a dashboard, for the user to access when they enter in correct login criteria. In this case we’re just going to use a page that has a basic header telling the user they have logged in correctly. The page can look something like this.

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>Sample Log In</title>
 
		<link rel="stylesheet" href="loginCSS.css" type="text/css" />
	</head>
	<body>
		<h1>You are now logged in!</h1>
		<a href="logout.php">Log Out Here</a>
	</body>
</html>

As you can see I have also included a log out link just below the h1 tag. If a user logs into the system we also want them to be able to log out. Next we’re going to create the SQL for our database. For this tutorial I’ll be using MySQL, however Oracle or SQL Server could also be used.

Note: If you’re going to use a different database then the code to connect to the database will be slightly different.

DROP TABLE IF EXISTS 'testDB'.'user'
 
CREATE TABLE 'testDB'.'user'
(
	'username' VARCHAR(10),
	'password' VARCHAR(10)
);
 
INSERT INTO 'testDB'.'user'
(username, password)
VALUES
('admin', 'password'),
('guest', 'password');

This is just a very simple database table that contains only a username and password. This script could obviously be modified to accept further fields of to encrypt the password field to increase the security of your system. Things like that will be out of the scope of this tutorial however.

Now that we have our environment set up we can start to use PHP to get data from the forms and compare them with the database. For the this tutorial we will only be using the POST method of retrieving data from forms. Using GET is often not recommended when getting sensitive data such as usernames and passwords. As you can see from the log in window, we have used the POST method to get the data, and when the form is submitted we are calling the userAuth.php file. Let’s go ahead and create that file now.

This block of code we will be using to check to see if the fields are blank. If they are we want to send them back to the login.html file to log back in again using the header() function. Next we want to enter all the configuration information to connect to the database and use some PHP functions to protect our site from SQL injection errors.

/*Create the variables to hold the database information*/
 
$dbName = "testDB";
 
/*Table name that we're checking against*/
 
$dbTable = "user";
 
/*Database username*/
 
$dbUsername = "DBUsername";
 
/*Database Password*/
 
$dbPassword = "DBPassword";
 
$username = $_POST(['username']);
$password = $_POST(['password']);
 
/*This next block is to prevent SQL injection hacks*/
$username = stripslashes($username);
$password = stripslashes($password);
 
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

I have put in default values into the variables. Variables such as $dbTable and $dbUsername will be subject to change based on your database configuration. These values will need to be filled in with correct values from your system. Next we’re going to be connecting to the database and opening a connection.

/*Connect to the Database*/
 
$connection = @mysql_connect("localhost", $dbUsername, $dbPassword) or die(mysql_error());
 
/*Select the database you want to access*/
 
$db = @mysql_select_db($dbName, $connection) or die(mysql_error());
 
/*Select statement from the database to see if the user is in the system*/
 
$sqlQuery = "SELECT COUNT(*) FROM $table_name WHERE username = '$username'
AND password = password('$password')";
 
/*Create a variable to hold the results of the SQL query*/
 
$result = @mysql_query($sqlQuery, $connection) or die(mysql_error());
 
/*Check the number of rows returned from the query*/
 
$num = mysql_num_rows($result);

Now we’re getting to the user authentication section. We’re now going to see if the number of rows that was selected is anything but 0. In theory it should ever only come back with 1 or 0 rows, however in systems where users can multiple accounts it’s good to keep it to != 0.

/*If the number of rows is not equal to 0 then authenticate the user*/
 
if ($num != 0)
{
	session_start();
 
	//Create a session for the username and password
	session_register($username);
	session_register($password);
 
	if(!session_is_registered($username))
	{
		header("location:login.html");
	}
	else
	{
		//because the user is authenticated move them to the dashboard
		header("Location: home.html");
	}
}
else
{
	header("Location: login.html");
	exit;
}
?>

We then register a session and store the username and password in the session. If the session has been registered correctly then you can send the user to the home screen. If the session is not registered correctly for some reason we don’t want the users accessing the system, so we send them back to the login screen to attempt to log in again.

That’s it, an entire login system. Of course this is just meant to give you the idea of the steps and should by no means be used in a real-world system as is. However you should have a firm understanding of how a basic login system works using PHP/MySQL and a little bit of HTML and CSS. As always if you have any questions/concerns feel free to leave a comment and I’ll get back to you asap.


4 Responses to “Intro to PHP – Creating a Basic Login System”

Leave a Reply