Hi all, after thinking for sometimes, I thought it will be grat opportunity to learn if I will start from scratch and build my own register/login system. Here is the thread that I will be posting the progress and I hope you guys will help me.

The code below is what I have so far. Just put two scripts in the same directory and that is! I hope you will help me :)
Thanks!
class.php

<?php
//php login sytem
class LoginRegister{
 function __construct(){
}

function displogin($status){
if ($status == "login"){
	// post login page
	$enc = base64_encode('login');
	$html = <<<LOGIN
	<form action = $_SERVER[PHP_SELF]?do=$enc, method = POST>
		<p>Username: <input type=text name = username /></p>
		<p>Password: <input type=password name = password /></p>
		<input type=submit value=Login />
	</form>
LOGIN;
		echo $html;
}//end if

else if ($status == "register"){
	//post register page
	$enc = base64_encode('register');
	$html = <<<LOGIN
	<form action = $_SERVER[PHP_SELF]?do=$enc, method = POST>
		<p>Username: <input type=text name = username /></p>
		<p>Password: <input type=password name = password /></p>
		<input type=submit value=Register />
	</form>
LOGIN;
		echo $html;
}// end elese if


}

function auth($username, $password){
	$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password' ";
	$res  = mysql_query($sql) or die(mysql_error());
	if (mysql_num_rows($res)==1){
	echo "sucessful logged in as ". $username;
	}//end if
	else{
		echo "<p style = 'color:red; font-weight:bold;'>Username or password not correct.
		<br /> New? Register!</p>";
		$this->displogin('register');
	}// end else
}


function checkempty($username, $password, $mode){
	if (empty($username) or empty($password)){
	echo "<p style = 'color:red; font-weight:bold;'>Empty Values are not allowed</p>";
	$this->displogin('login');
	}//end if
	else{
	//do checking
	switch($mode){
		case 'login':
		$this->auth($username, $password);
		case 'register':
		$this->adduser($username, $password);
		default:
			echo "<p style = 'color:red; font-weight:bold;'>Wrong Values are not allowed</p>";
			$this->displogin('login');
		}//end switch
	}//end else
}

function login($uname, $passwd){
	//username
	$username = stripslashes($uname);
	$username = mysql_real_escape_string($uname);
	//passsword	
	$password = stripslashes($passwd);
	$password = mysql_real_escape_string($passwd);
	//check for empty variables
	$this->checkempty($username, $password, 'login');	
}
	
function register($uname, $passwd){
	//username
	$username = stripslashes($uname);
	$username = mysql_real_escape_string($uname);
	//passsword	
	$password = stripslashes($passwd);
	$password = mysql_real_escape_string($passwd);
	//check for empty variables
	$this->checkempty($username, $password, 'register');	
}
	
function adduser($username, $password){
	$sql = "INSERT INTO users(username, password) VALUES('$username', '$password')";
	//redirect to login page
	echo "<p style = 'color:green; font-weight:bold;'>Thanks for registering. You can now login</p>";
	$this->displogin('login');
	mysql_query($sql) or die(mysql_error());
}

}//end class
?>

index.php

<?php
require "class.php";
$obj = new  LoginRegister();
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("admin", $conn)or die(mysql_error());
if ((isset($_GET['do']))){
	if (($_GET['do'])==(base64_encode('login'))){
	$obj->login($_POST['username'], $_POST['password']);
	 }//end middle first if
	 else if(($_GET['do'])== (base64_encode('register'))){
		$obj->register($_POST['username'], $_POST['password']);
	 }
	 else{
		 echo "<p style = 'color:red; font-weight:bold;'>Please Login</p>";
		$obj->displogin('login');	
		//debug
		echo base64_encode('login').'<br />';
		echo $_GET['do'];
	 }//end else middle
	 
}//end last if 
else{
	echo "<p style = 'color:green; font-weight:bold;'>Please Login</p>";
	$obj->displogin('login');	
}//end else
?>

Recommended Answers

All 16 Replies

Any help feature or criticism is allowed. Also modification et al
feel free to comment anything :)

Hey.

I would recommend trying to keep logic classes clear of output. One of the fundamental ideas behind OOP is code re-usability, and by infusing the front-end code into the logic you are limiting the uses of the class to a single front-end.

What if, down the line, you need to provide XML output for use login, rather than HTML? Like say, if you decided to implement client-side login via AJAX.

For example, this class would only be useful by a HTML page:

<?php
class Member
{
    public function authenticate($name, $password)
    {
        if(/* authentic */1) {
            echo '<span style="color: green;">Success!</span>';
        }
        else {
            echo '<span style="color: red;">I\'m afraid I can\'t do that, {$name}.</span>';
        }
    }
}
?>
<html>
<body>
    <div>
    <?php
    $member = new Member();
    $member->authenticate('input', 'more input');
    ?>
    </div>
</body>
</html>

While this one could be used to generate any output:

<?php
class Member
{
    public function authenticate($name, $password)
    {
        if(/* authentic */1) {
            return true;
        }
        else {
            return false;
        }
    }
}
?>
<html>
<body>
    <div>
    <?php
    $member = new Member();
    if($member->authenticate('input', 'more input')) {
        echo '<span style="color: green;">Success!</span>';
    }
    else {
        echo '<span style="color: red;">I\'m afraid I can\'t do that, {$name}.</span>';
    }
    ?>
    </div>
</body>
</html>
<root>
    <?php
        $member = new Member();
        $result = $member->authenticate('input', 'more input');
    ?>
    <result message="<?php echo $result ? "success" : "failure"; ?>"/>
</root>

See what I mean? ;-)

I see,
Can you help me point out method names that you see will prevent reuse? I see that I should change all login prompts may be to use XML (is that what you said?). But I'm afraid I might forget some. So pointing methods that need to be removed/changed for sake of re-use will be great help to me.

Another thing is, I have not learned Ajax.
All I have is the basics of both JavaScript and XML, but not anything Ajaxed.
Anyway, is ajax "long curve" to learn? I would be happy to learn and implement that.

I appreciate your reply, which is great :)

I see,
Can you help me point out method names that you see will prevent reuse? I see that I should change all login prompts may be to use XML (is that what you said?). But I'm afraid I might forget some. So pointing methods that need to be removed/changed for sake of re-use will be great help to me.

Another thing is, I have not learned Ajax.
All I have is the basics of both JavaScript and XML, but not anything Ajaxed.
Anyway, is ajax "long curve" to learn? I would be happy to learn and implement that.

I appreciate your reply, which is great :)

AJAX is JavaScript.
The easiest way to implement it would be using a library, such as jQuery or the scriptaculous ones.

Be aware that 'AJAX' requires JavaScript to be available, so design your sites to work without it.

Can you help me point out method names that you see will prevent reuse?

In your class the auth, checkempty and adduser methods should ideally not echo HTML, but rather return a boolean or an error code.
The displogin method also echoes HTML, but it can hardly be considered a logic method. It's more a HTML-specific display method. I would actually argue that it doesn't belong to that class, but rather in the HTML page itself, but that's a different matter.

As a side-note. You should try to avoid abbreviating your method names, like "auth". Even if it seems obvious to you what it stands for at the moment, it may not seem that obvious in the future, if you, or whoever receives your code, ever need to review it.

It's best to adopt a good naming convention and stick to it throughout the project. The PHP "standard" is to use all-lower case names, using _ to separate words. ('authenticate', 'check_empty', 'add_user').
Personally, I like the C# naming conventions. ('Authenticate', 'CheckEmpty', 'AddUser'). It allows me to more clearly distinguish between public and private methods. ('PublicMethod', 'privateMethod')

I see that I should change all login prompts may be to use XML (is that what you said?)

Not really, no. The XML example was just to demonstrate how the code could be reused for a different purpose other than to print HTML. You don't need to worry about this until you need to print something other than HTML.

Another thing is, I have not learned Ajax.
All I have is the basics of both JavaScript and XML, but not anything Ajaxed.
Anyway, is ajax "long curve" to learn? I would be happy to learn and implement that.

AJAX is just a method used by client-side code (JavaScript, usually) to fetch data from the server without having to do a full refresh. The AJAX code itself is fairly simple, but to use it you need to write the client-side (JavaScript) code that uses the data it retrieves.

Check out the W3Schools AJAX tutorial. It explains the basics of AJAX very quickly.

Just keep your classes separate by thinking of what they are there for.

The classes/methods that access the database or some other datastore and (auth($username, $password)) process logic (also known as the Model or DAO - Data Access Objects) should be separated from classes/methods that just display some information given by the model (displogin($status)) - also known as the View.

Having controller classes sit in the middle and use different view classes (As Atli said, HTML, XML or Ajax) depending on your need is a good idea.

Do some research on the MVC pattern, it is really useful.

Thanks guys for your criticism and suggestions. What I say is, they are really really great! They help me improve and I will work on them and make an improved code. Before I implement above suggestions, here is what I have thought to do:
1. Separate into 3 classes (Database Connection, Login logic, Displaying HTML messages)
2. Apply naming Standard as Atli said (I loved that as I use them in Pythoning) :)
3. Check libraries like JQuery like Gresham said and take alook at Ajax

More suggestions and criticism are invited. Anyway, after it stands well I will add some security tightening like sessions, deciphering, et al

Thanks guys for your criticism and suggestions. What I say is, they are really really great! They help me improve and I will work on them and make an improved code. Before I implement above suggestions, here is what I have thought to do:
1. Separate into 3 classes (Database Connection, Login logic, Displaying HTML messages)
2. Apply naming Standard as Atli said (I loved that as I use them in Pythoning) :)
3. Check libraries like JQuery like Gresham said and take alook at Ajax

More suggestions and criticism are invited. Anyway, after it stands well I will add some security tightening like sessions, deciphering, et al

I completely re-wrote the whole class at home. I added features like encryption, email check et al. I will post it tomorrow as I left laptop at home. Thanks for suggestions.

Here is my new class and login page I wrote at home. It have registration capabilities

<?php

require('inc.class.php');
//testing values
$sms = new HtmlSms();
$logger = new LoginRegister();
if (!isset($_GET['do'])){
    $sms->login();
}//end if
else{
    if ($_GET['do']=='login'){
        $ret = $logger->Validate($_POST['username'], $_POST['password']);
        if($ret ==0){        
            header("Location:members.php");
            die("No hacking here!");
        }//end if
        else{        
            $sms->error($ret);
        }
        
    }//end if
    else if($_GET['do']=='register'){
    if (isset($_POST['submit'])){
         $err = $logger->register($_POST);
         if($err !=0){
             $sms->error($err);
         }//end if
         else{
            $err = $logger->validateform();
            if($err !=0){
             $sms->error($err);
            }//end if
            else{
                echo "Successful registered!";
            }//end else
         }//end else
    }//end if
    else{
        $sms->register();
    }
}//end elif

    else if($_GET['do']=='logout'){
    $logger->logout();
    header("Location:index.php");
}//end elif
}
?>
<?php
//start session
session_start();
class Database{
    //for db
    var $host;
    var $dbusername;
    var $dbpasswd;
    var $db;
    //for pagination
    //max page numbers
    var $page_count;
    //max contents per page
    var $per_page;
    
    function __construct($usr, $pass, $host, $db){
	    $this->host = $host;
	    $this->dbusername = $usr;
	    $this->dbpasswd = $pass;
	    $this->db = $db;
        
    }
    
    // connect db
    function connect(){
    $conn = mysql_connect($this->host, $this->dbusername, $this->dbpasswd) or die (mysql_error());
    mysql_select_db($this->db, $conn) or die(mysql_error()); 
    return $conn;
    }
}//end class db

class LoginRegister extends Database{
    //credentials - fname, lname, email, username, password
    var $firstname;
    var $lastname;
    var $email;
    var $username;
    var $password;
    var $date;
    
    function __construct(){
        parent::__construct('root', 'jesus', 'localhost', 'testlogin');
    }
    
    function Authenticate($user, $passwd){
        $username = mysql_real_escape_string($user);
        $password = $this->encrypt(mysql_real_escape_string($passwd));
        //connect
        $conn = $this->connect();
        $query = "SELECT * FROM users WHERE username = '$username'";
        $res = mysql_query($query);
       if (mysql_num_rows($res)==1){
            //user exists
            $row = mysql_fetch_assoc($res);
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
            $fname = $row['firstname'];        
            //password check
            if ($dbusername == $username && $dbpassword == $password){
            //correct passwd
            //call function to set something useful for sessions
            $_SESSION['username'] = $dbusername;
            $_SESSION['fname'] = $fname;
            $_SESSION['who'] = 1;
            }//end if
            else{
            //incorrect passwd
            return 2;
            }//end else
            
       }//end if
       else{
       //user doesn't exists
       return 1;
       }//end else
        
    }
    
    function validate($usr, $pass){
        $usr = trim($usr);
        $pass = trim($pass);
        if (empty($usr)&&empty($pass)){
        return 5;
        }//end if
        else if (empty($usr)){
        return 3;
        }//end elif
        else if (empty($pass)){
        return 4;
        }//end elif
        else{
        //both field submitted -- Authenticate
        //connect to server
        $this->connect();
        $res = $this->Authenticate($usr, $pass);
        return $res;
        }//end else
    }
    
    function logout(){
    session_destroy();    
    }
    
    function validateemail($email){
        $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (filter_var($sanitized, FILTER_VALIDATE_EMAIL)) {
            $this->email = $sanitized;
            return 0;
        }//end if
        else{
            return 10;
        }//end else
    }
    
    function validateusername($usr){
        $this->connect();
       $usr = mysql_real_escape_string($usr);
       $res = mysql_query("SELECT username from users WHERE username = '$usr'") or die(mysql_error());
       if(mysql_num_rows($res)>0){
        return 11;
       }//end if
       else{
       return 0;
       }//end else
       
       
    }
    
    //call this only after register/validateform is successful
    function registerme(){    
        $conn = $this->connect();
        $query = "INSERT INTO users(firstname, lastname, email, username, password, date) VALUES('$this->firstname', '$this->lastname', '$this->email', '$this->username', '$this->password', ' $this->date')  ";
        mysql_query( $query) or die(mysql_error());
    
    }
    
    function encrypt($pass){
        //do all encrypt stuffs here
        return sha1($pass);
    }
    
    //call this only after register is successful
    function validateform(){
        $usr = $this->username;
        $fname = $this->firstname;
        $lname = $this->lastname;
        $email = $this->email;
        $uname = $this->username;
        $passwd = $this->password;
        if (strlen($fname )>25 or strlen($lname )>25 or strlen($uname )>25 or strlen($passwd )>25){
            return 8;
        }//end if 
        else{
                if(strlen($passwd)<6){
                return 9;
                }//end if
                else if (($this->validateusername($usr))>0){
                    return 11;
                }//end elif
                else if(($this->validateemail($email))==0){  
                    $this->password = $this->encrypt($passwd);
                    $this->registerme();
                    return 0;
                }//end if
                else{
                    return 10;
                    }//end else
        }//end else
        
    
    }
    
    function register($arr){
        //array of fname, lname, email, username, password
        //form data
        $this->firstname = strip_tags($arr['fname']);
        $this->lastname = strip_tags($arr['lname']);
        $this->email = strip_tags($arr['email']);
        $this->username = strtolower(strip_tags($arr['username']));
        $password = strip_tags($arr['password']);
        $rpassword = strip_tags($arr['rpassword']);
        $this->date = Date("Y-m-d H:i:s");
        
        if( $this->firstname && $this->lastname && $this->email && $this->username && $password && $rpassword){
            //echo " $date/$firstname $lastname /$email/$username/$password /$rpassword ";            
            $this->$password = $password ;
            if( $this->encrypt($password) ==  $this->encrypt($rpassword)){
                 $this->password = $password;            
                return 0;
            }//end if
            else{
                return 7;
            }
            
        }//end if 
        else{
            //blank field(s)
            return 6;
        }
    }
    
}//end class 


class HtmlSms{
/*
error codes
* 0 = successful
* 1 = username wrong
* 2 = password wrong
* 3 = unsubmitted username
* 4 = unsubmitted password
* 5 = empty username and passwd
//registration codes
* 6 empty field
* 7 password don't match
* 8 one field is more than 25 characters
* 9 password field is less than 6
* 10 invalid email
* 11 username already exists // forgot password?


*/

    function login(){
    $html = <<<HTML
    <form method='POST' action = 'index.php?do=login'>
    <p>Username: <input name='username' type = 'text'></p>
    <p>Password: <input name='password' type = 'password'></p>
    <input value = 'login' type = 'submit'>
    </form>    
    <a href='index.php?do=register'>Register</a>
HTML;
echo $html;
    
    }
    
     
    function register(){
    echo "<h1>Register</h1>";
        $html = <<<HTML
        <form method='POST' action = 'index.php?do=register'>
            <html>
                <table cellpadding='5px'>
                    <tr>
                        <td> Your First Name</td>
                        <td><input name='fname' type = 'text'> </td>
                    </tr>
                    
                    <tr>
                        <td> Your Last Name</td>
                        <td><input name='lname' type = 'text'> </td>
                    </tr>
                    
                    <tr>
                        <td> Email address</td>
                        <td><input name='email' type = 'text'> </td>
                    </tr>
                    
                     <tr>
                        <td> Choose a User Name</td>
                        <td><input name='username' type = 'text'> </td>
                    </tr>
                    
                    <tr>
                        <td>Choose a password</td>
                        <td><input name='password' type = 'password'> </td>
                    </tr>
                    
                    <tr>
                        <td>Repeat your password</td>
                        <td><input name='rpassword' type = 'password'> </td>
                    </tr>
                </table>
            </html>
            <p>  <input name = submit value = 'register' type = 'submit'></p>
        </form>
HTML;
echo $html;
    }
    
    function error($ecode){
        switch($ecode){
            case 1:
                echo "<p style = 'color:red; font-weight:bold;'>Incorrect Username</p>";
                $this->login();
                break;
            case 2:
                echo "<p style = 'color:red; font-weight:bold;'>Incorrect Password</p>";
                $this->login();
                break;
            case 3:
                echo "<p style = 'color:red; font-weight:bold;'>Blank usernames are not allowed!</p>";
                $this->login();
                break;
            case 4:
                echo "<p style = 'color:red; font-weight:bold;'>Blank passwords are not allowed!</p>";
                $this->login();
                break;
            case 5:
                echo "<p style = 'color:red; font-weight:bold;'>Blank usernames and passwords are not allowed!</p>";
                $this->login();
                break;
            case 6:
                echo "<p style = 'color:red; font-weight:bold;'>Blank fields are not allowed!. Please fill <b>all</b> fields</p>";
                $this->register();
                break;
            case 7:
                echo "<p style = 'color:red; font-weight:bold;'>Passwords doesn't match! </p>";
                $this->register();
                break;
            case 8:
                echo "<p style = 'color:red; font-weight:bold;'>No Field can exceed 25 Characters!</p>";
                $this->register();
                break;
            case 9:
                echo "<p style = 'color:red; font-weight:bold;'>Your password must be between 6 and 25 characters</p>";
                $this->register();
                break;
            case 10:
                echo "<p style = 'color:red; font-weight:bold;'>Your Email is invalid</p>";
                $this->register();
                break;
            case 11:
                echo "<p style = 'color:red; font-weight:bold;'>The username is already taken, please choose another one!</p>";
                $this->register();
                break;
                    
            }//end switch
    }
  
}//end class htmlsms


?>
<?php
require('inc.class.php');
if(isset($_SESSION['who'])&& ($_SESSION['who']=1)){
$name = $_SESSION['fname'];
echo "Welcome $name, this page you are viewing is for members, of which you are one! <br /><a href='index.php?do=logout'>logout</a>";
}//end if 

else{
$sms = new HtmlSms();
echo "<span style = 'color:red;'>Access denied! You aren't logged in<br />So please login or <a href='register.php'>Register</a></span>" ;
$sms->login();
}//end else


?>

my databse name was testlogin and table users. Here is a script to install table fields necessary

<?php
mysql_connect('localhost', 'root', 'jesus');
mysql_select_db('testlogin');
mysql_query("DROP TABLE IF EXISTS users ") or die(mysql_error());
$query = " CREATE TABLE `testlogin`.`users` (`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `firstname` VARCHAR(25) NOT NULL, `lastname` VARCHAR(25) NOT NULL, `email` VARCHAR(25) NOT NULL, `username` VARCHAR(25) NOT NULL, `password` VARCHAR(100) NOT NULL, `date`DATETIME NOT NULL, UNIQUE (`email`, `username`)) ENGINE = MyISAM";
mysql_query($query) or die(mysql_error());
echo 'successful created users table';

?>

my databse name was testlogin and table users. Here is a script to install table fields necessary

<?php
mysql_connect('localhost', 'root', 'jesus');
mysql_select_db('testlogin');
mysql_query("DROP TABLE IF EXISTS users ") or die(mysql_error());
$query = " CREATE TABLE `testlogin`.`users` (`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `firstname` VARCHAR(25) NOT NULL, `lastname` VARCHAR(25) NOT NULL, `email` VARCHAR(25) NOT NULL, `username` VARCHAR(25) NOT NULL, `password` VARCHAR(100) NOT NULL, `date`DATETIME NOT NULL, UNIQUE (`email`, `username`)) ENGINE = MyISAM";
mysql_query($query) or die(mysql_error());
echo 'successful created users table';

?>

I still need you experts to poke around above code and correct me anywhere due to security/coding habits/OOP stuffs et al and all you can suggest for the above code. I'm novice on PHP security issues and I

thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.