Simple PHP User Authentication Login System
Note: the following code is for educational purposes only, and should not be deployed on any mission-critical systems or websites that require authentication. This post is best used as a tool to help understand the underlying concept of a basic PHP user login system and merely shows a simple example.
A good user-login system should do three things:
- 1. Allow the user to enter a username and password.
- 2. Validate that information and return success or otherwise.
- 3. Perform basic checks on $_SESSION login after the initial login.
The scope of this particular article will focus on the first stage of authentication, which centers on validating user input and establishing a very basic authentication scheme. In later articles, coders will focus on the more advanced concepts of security salts, and techniques to continue validation well after the user has initially logged in, by checking information just as the user’s browser agent and login time.
Assumptions: This tutorial will be using MySQL and PHP. Apache as a server platform is not required, and any server that allows PHP to manage a HTTP POST will work.
For the back end storage solution, many coders may choose to use one of the two versions of MySQL that are included by most shared hosting and VPS providers. With proper scaling configuration, MySQL can handle large sites with hundreds of thousands of users and even by default can handle most any variant of this tutorial.
There are five basic bits of information that are prudent for any login system: the user ID (which should start at zero and increment up for each new user), the users name, password and email, and finally the user-agent string from the browser they logged in through. This user agent string will be updated on each successful login, and can be used to determine if a user is being subjected to a man in the middle attack (which is more advanced, and will be covered in another post). Insert the following SQL statement into phpMyAdmin or MySQL to create the user table.
CREATE TABLE siteusers( u_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, u_name VARCHAR(32) NOT NULL, u_password VARCHAR(32) NOT NULL, u_email VARCHAR(128) NOT NULL, u_useragent VARCHAR(128) NOT NULL ) ENGINE = MYISAM ;
On the front end, the HTML form consists of three inputs: the username, password and submit button. For now the form code can be placed in a separate form.html file, however the PHP script will not execute unless the method attribute is changed to the correct file path. At the end of this tutorial, all the code is put together and can be safely contained within one single login.php file.
<form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Username: <input type="text" name="username" /><br /> Password: <input type="password" name="password" /><br /> <input type="submit" value="Login.." /><br /> </form>
The following twenty lines of code contain limited commenting, however it is rather easy to understand. Step by step, this code simply detects the browsers state and acts accordingly. If the browser has issued a POST statement, it means the user has likely entered their login credentials and pressed the submit button. From there, it connects to a defined MySQL database and captures the POST variables. Here is where things might get tricky, and require further explaination.
One effective way to deter SQL injection attacks is to escape any variables before using them within a SQL query. This means that PHP adds a back-slash in front of any quotation marks or apostrophes, thus preventing MySQL from unknowingly executing multiple statements (such as defaulting the user ID to an administrator, or forcing MySQL to empy the table entirely). PHP added a function called mysql_escape_string() that can be used as a preemptive measure for SQL injections and malicious users destroying data.
The second part is to calculate a MD5 hash of the password, and this is done so that if an attacker gains access to the database, they will only encounter a list of thirty-two character hashes rather than plaintext passwords. Converting those hashes into the original passwords would take lots of computer power to create a MD5 collision, and not many attempts to do this have been successful. The second section of this tutorial will cover the salt concept, which adds a secondary string to the MD5 calculation, which makes it even harder to convert.
Once the HTTP POST variables are processed, the code then queries the database that was created in the first step for the following: if there is a user with the same username and password as was submitted, return their information; otherwise stop. After this executes, the mysql_num_rows() function counts how many users matched the original query and returns that number. If its zero, the script simply redisplays the login form with an error message claiming the info was invalid, however if one or more users matched, then their username is added into the $_SESSION scope, which is used to validate the user on each subsequent page view.
<?php
// Edit: select your database here
mysql_select_db("database-name");
if($_POST){
$tempuser = mysql_escape_string($_POST['username']);
$temppass = md5(mysql_escape_string($_POST['password']));
$res = mysql_query("select * from siteusers where u_name='$tempuser'
and u_password='$temppass'");
$num = mysql_num_rows($res);
if($num == 0){
// user entered wrong username or pass; not logged in
echo "Invalid username or password.";
}else{
// user is logged in
$_SESSION['uname'] = $tempuser;
}
}
?>
Connecting it all together, the login form can be returned from within a function, and placed inside of the PHP script, thus condensing everything into thirty or so lines of code.
<?php
// Edit: select your database here
mysql_select_db("database-name");
function showLoginForm($msg){
$tempMsg = ($msg) ? $msg : "Please login:";
$temp = "
<b>$tempMsg</b><br />
<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">
Username: &l;tinput type=\"text\" name=\"username\" /><br />
Password: &l;tinput type=\"password\" name=\"password\" /><br />
<input type=\"submit\" value=\"Login..\" /><br />
</form>";
return $temp;
}
if($_POST){
$tempuser = mysql_escape_string($_POST['username']);
$temppass = md5(mysql_escape_string($_POST['password']));
$res = mysql_query("select * from siteusers where u_name='$tempuser'
and u_password='$temppass'");
$num = mysql_num_rows($res);
if($num == 0){
// user entered wrong username or pass; not logged in
echo showLoginForm("Invalid username or password.");
}else{
// user is logged in
$_SESSION['uname'] = $tempuser;
echo "Welcome back, " . $_SESSION['uname'];
}
}
?>
As a reminder, this tutorial covered the basic concept of using PHP to authenticate a user. The next part will cover more advanced topics, such as salts, browser strings and using timestamps to expire a users login session.

Jules Cesar
Oct 27
Thanx! just waiting 4 da next part
You!