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.
[html] 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.
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);