Recommended sites
Web Hosting Reviews

Creating a file based login system

In this tutorial I will show you how to create a file based login system to register, login and logout users. You can use this method without any database.

Creating a file based login system

In this tutorial I will show you how to create a file based login system to register, login and logout users. You can use this method without any database.

Step 1.
First of all we have to collect what we need. The main goal is to restrict access to some of our web pages and allow access only registered users. To do this each webpage must check whether the current visitor is logged in or not.
In general a basic but complete user management requires the following functions:

  • User login
  • User logout
  • Register user
  • Check whether user is logged in

To realise this in PHP we will create the following files:
  • login.php - Contains the HTML form to allow user login and calls the login function.
  • logout.php - Contains the HTML form to allow user logout and calls the logout function.
  • register.php - Contains the HTML form to allow a visitor to register and call the registration function.
  • common.php - Contains the main PHP function to separate the code and design.
  • test.php - A test page to demonstarte the functionality.

You can see a demonstration of login system and you can download complete login system.

Step 2.
To login a user first of all we have to register. So let's create a function first to register user and store registartion information in a file.

function registerUser($user,$pass1,$pass2)

We will get the parameters from the registration form (see in the next step). During the registartion we need to check the followings:
  • User already exists or not
  • Passwords match or not
  • Password are long enough

If all of these are ok, than we can store the username and password in the file. To make the system more secure we will store the passwords in an md5 format. The registration code is below and it is stored in the common.php file:

<?php
function registerUser($user,$pass1,$pass2){
    
$errorText = '';
    
    
// Check passwords
    
if ($pass1 != $pass2) $errorText = "Passwords are not identical!";
    elseif (
strlen($pass1) < 6) $errorText = "Password is to short!";
    
    
// Check user existance    
    
$pfile = fopen("userpwd.txt","a+");
    
rewind($pfile);

    while (!
feof($pfile)) {
        
$line = fgets($pfile);
        
$tmp = explode(':', $line);
        if (
$tmp[0] == $user) {
            
$errorText = "The selected user name is taken!";
            break;
        }
    }
    
    
// If everything is OK -> store user data
    
if ($errorText == ''){
        
// Secure password string
        
$userpass = md5($pass1);
        
        
fwrite($pfile, "rn$user:$userpass");
    }
    
    
fclose($pfile);
    
    
    return 
$errorText;
}
?>

[newpage=Part 2]
Step 3.
Now create a register form. User needs to specify a user name a password and he/she needs to confirm the password. It means that we need a text field and 2 password fields on the registration form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="registerform">
        <table width="100%">
          <tr><td>Username:</td><td> <input name="username" type="text"  /></td></tr>
          <tr><td>Password:</td><td> <input name="password1" type="password" /></td></tr>
          <tr><td>Confirm password:</td><td><input name="password2" type="password" /></td></tr>
          <tr><td colspan="2" align="center"><input type="submit" name="submitBtn" value="Register" /></td></tr>
        </table>
      </form>
</body>
</html>

As I mentioned abowe the main function will be implemented in a separate file called common.php (See in Step 2.) so in this file we just call registerUser() function with the username and passwords. Depending on the function was success or not we display a message to the user.
So the complete register form (register.php) looks like this:

<?php
    
require_once('common.php');

    if (isset(
$_POST['submitBtn'])){
        
// Get user input
        
$username  = isset($_POST['username']) ? $_POST['username'] : '';
        
$password1 = isset($_POST['password1']) ? $_POST['password1'] : '';
        
$password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
        
        
// Try to register the user
        
$error = registerUser($username,$password1,$password2);
    }    
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php if ((!isset($_POST['submitBtn'])) || ($error != '')) {?>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="registerform">
        <table width="100%">
          <tr><td>Username:</td><td> <input name="username" type="text"  /></td></tr>
          <tr><td>Password:</td><td> <input name="password1" type="password" /></td></tr>
          <tr><td>Confirm password:</td><td><input name="password2" type="password" /></td></tr>
          <tr><td colspan="2" align="center"><input type="submit" name="submitBtn" value="Register" /></td></tr>
        </table>
      </form>
<?php
}
    if (isset(
$_POST['submitBtn'])){
?>
        <table width="100%"><tr><td><br/>
<?php
    
if ($error == '') {
        echo 
" User: $username was registered successfully!<br/><br/>";
        echo 
' <a href="login.php">You can login here</a>';
    }
    else echo 
$error;
?>
        <br/><br/><br/></td></tr></table>
<?php
    
}
?>
</body>
</html>

[newpage=Part 3]
Step 4.
We are able to register users so we want to login now. To do this we implement a new function function loginUser($user,$pass)
In this function we get the username and password as parameter and try to find this pair in the password file. If the login was success than we set a session variable.
The code is stored in the common.php file and looks like this:

<?php
function loginUser($user,$pass){
    
$errorText = '';
    
$validUser = false;
    
    
// Check user existance    
    
$pfile = fopen("userpwd.txt","r");
    
rewind($pfile);

    while (!
feof($pfile)) {
        
$line = fgets($pfile);
        
$tmp = explode(':', $line);
        if (
$tmp[0] == $user) {
            
// User exists, check password
            
if (trim($tmp[1]) == trim(md5($pass))){
                
$validUser= true;
                
$_SESSION['userName'] = $user;
            }
            break;
        }
    }
    
fclose($pfile);

    if (
$validUser != true) $errorText = "Invalid username or password!";
    
    if (
$validUser == true) $_SESSION['validUser'] = true;
    else 
$_SESSION['validUser'] = false;
    
    return 
$errorText;    
}
?>

Step 5.
Now create a login form. It is similar to the registration form but here we need only one password field. Besides this we can put a link to the registration form to let the visitor register if neccessary. During the processing of the form we will call our loginUser function, created in Step 4.
The login.php file content is the following:


<?php
require_once('common.php');

$error = '0';

if (isset(
$_POST['submitBtn'])){
    
// Get user input
    
$username = isset($_POST['username']) ? $_POST['username'] : '';
    
$password = isset($_POST['password']) ? $_POST['password'] : '';
        
    
// Try to login the user
    
$error = loginUser($username,$password);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<?php if ($error != '') {?>
      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
        <table width="100%">
          <tr><td>Username:</td><td> <input name="username" type="text"  /></td></tr>
          <tr><td>Password:</td><td> <input name="password" type="password" /></td></tr>
          <tr><td colspan="2" align="center"><input type="submit" name="submitBtn" value="Login" /></td></tr>
        </table>
      </form>

      &nbsp;<a href="register.php">Register</a>
<?php
}
    if (isset(
$_POST['submitBtn'])){
?>
        <table width="100%"><tr><td><br/>
<?php
    
if ($error == '') {
        echo 
"Welcome $username! <br/>You are logged in!<br/><br/>";
        echo 
'<a href="test.php">Now you can visit the index page!</a>';
    }
    else echo 
$error;

?>
        <br/><br/><br/></td></tr></table>
<?php
    
}
?>
</body>
</html>

[newpage=Part 4]
Step 6.
The next step is to logout the user. To realise this we will implement anew method in the common.php file. The function is function logoutUser()
The function is quite easy. It only removes the user session variables and looks like this:

<?php
function logoutUser(){
    unset(
$_SESSION['validUser']);
    unset(
$_SESSION['userName']);
}
?>

Step 7.
We create a logout.php file which is as simple as the logoutUser function. We just call the function and redirect the user the the test page. The code is this:

<?php
    
require_once('common.php');
    
logoutUser();
    
header('Location: test.php');
?>

Step 8.
Ok, now we can login, logout and register user, but how to check that there is a logged in user? It is not so complicated as well. We need to check whether the session variables are set or not. If the user is not logged in than we redirect to the login page. There he/she can decide to login or register. To implement this functionality we will create a checkUser function in the common.php file with the following content:

<?php
function checkUser(){
    if ((!isset(
$_SESSION['validUser'])) 
         || (
$_SESSION['validUser'] != true)){
        
header('Location: login.php');
    }
}
?>

[newpage=Part 5]
Step 9.
Let's summarise the complete content of the common.php file.


<?php

session_start
();

function 
registerUser($user,$pass1,$pass2){
    
$errorText = '';
    
    
// Check passwords
    
if ($pass1 != $pass2) 
        
$errorText = "Passwords are not identical!";
    elseif (
strlen($pass1) < 6) 
        
$errorText = "Password is to short!";
    
    
// Check user existance    
    
$pfile = fopen("userpwd.txt","a+");
    
rewind($pfile);

    while (!
feof($pfile)) {
        
$line = fgets($pfile);
        
$tmp = explode(':', $line);
        if (
$tmp[0] == $user) {
          
$errorText = "The selected user name is taken!";
          break;
        }
    }
    
    
// If everything is OK -> store user data
    
if ($errorText == ''){
        
// Secure password string
        
$userpass = md5($pass1);
        
        
fwrite($pfile, "rn$user:$userpass");
    }
    
    
fclose($pfile);
    
    
    return 
$errorText;
}

function 
loginUser($user,$pass){
    
$errorText = '';
    
$validUser = false;
    
    
// Check user existance    
    
$pfile = fopen("userpwd.txt","r");
    
rewind($pfile);

    while (!
feof($pfile)) {
        
$line = fgets($pfile);
        
$tmp = explode(':', $line);
        if (
$tmp[0] == $user) {
            
// User exists, check password
            
if (trim($tmp[1]) == trim(md5($pass))){
                
$validUser= true;
                
$_SESSION['userName'] = $user;
            }
            break;
        }
    }
    
fclose($pfile);

    if (
$validUser != true) 
       
$errorText = "Invalid username or password!";
    
    if (
$validUser == true) $_SESSION['validUser'] = true;
    else 
$_SESSION['validUser'] = false;
    
    return 
$errorText;    
}

function 
logoutUser(){
    unset(
$_SESSION['validUser']);
    unset(
$_SESSION['userName']);
}

function 
checkUser(){
    if ((!isset(
$_SESSION['validUser'])) 
         || (
$_SESSION['validUser'] != true)){
        
header('Location: login.php');
    }
}

?>

Step 10.
As final step let's create a test page to demonstarte the system is working.

<?php
    
require_once('common.php');
    
checkUser();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
   Login System Demo Page
   Hello <?php echo $_SESSION['userName']; ?> ! <br/>
   <p>This site demonstartes how to use Login System.</p>
   <p><a href="logout.php"> To log out click here!</a></p>
</body>

Sponsored links