Creating a file based login system



by Administrator author list


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))){
                
$validUsertrue;
                
$_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>
[/html]


article index
page 1 : untitled page
page 2 : Part 2
page 3 : Part 3
page 4 : Part 4
page 5 - current : Part 5


Tags:

Php Toys - 2006 - Php resources, scripts and tutorials - Privacy Policy
Insurance Index - Tutorial collection - Forex trading, brokers, reviews - Mortgage payment calculator
{THEMEDISCLAIMER}
Render time: 0.1276 sec, 0.0234 of that for queries. DB queries: 25.