Friday, January 31, 2014

Approach Of object-oriented in PHP for Login system- read more @i-visionblog

The world is about the defining classes with data & functions where they can be accessed by real world objects.My last post on PHP login system-Easy Login System is simple way of loging inside a web connecting MySQL,So let us see about approach on Object oriented programming in PHP. Object oriented leads to manage your codes by implementing function and data seperately which interacts with the real world.This post enables you to understand in deeper about usages of classes and object start up.

Uses of Object-Oriented:

1)It let's the developers to manage their codes efficiently and more over they can update their codes if there is need
2)They could manage the data thats's used in the program and prevent the duplication of data flow inside the program
3)Object oriented approach gives you clear map about the working of the system.

How Easily we could code it ?

SQL statement :
this enables you to create a Table in Database for maintaing and handling Data for users.I had mentioned few fields for demo.



CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=armscii8 AUTO_INCREMENT=2 ;
INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, 's.shivasurya', '13IT102');


So let us create a Class for our manage functions and data members efficiently.

function_data_class.php


<?php
class login_user
{
    var $username;
    var $pwd;
    var $database;
    var $tablename;
    var $connection;
    var $random_key;
    var $error_message;

function GetErrorMessage()
    {
        if(empty($this->error_message))
        {
            return '';
        }
        $errormsg = nl2br(htmlentities($this->error_message));
        return $errormsg;
    }  
function HandleError($err)
    {
        $this->error_message .= $err."\r\n";
    }
 
    function HandleDBError($err)
    {
        $this->HandleError($err."\r\n mysqlerror:".mysql_error());
    }
 
function DBinitialize($host,$uname,$pwd,$database,$tablename)
    {
        $this->db_host  = $host;
        $this->username = $uname;
        $this->pwd  = $pwd;
        $this->database  = $database;
        $this->tablename = $tablename;
     
    }
   function SetRandomKey($key)
    {
        $this->random_key = $key;
    }
    function Login()
    {
        if(empty($_POST['username']))
        {
            $this->HandleError("Username is empty!");
            return false;
        }
     
        if(empty($_POST['password']))
        {
            $this->HandleError("Password is empty!");
            return false;
        }
     
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
     
        if(!isset($_SESSION)){ session_start(); }
        if(!$this->query_db($username,$password))
        {
            return false;
        }
     
        $_SESSION[$this->GetLoginSessionVar()] = $username;
     
        return true;
    }
 
    function CheckLogin()
    {
         if(!isset($_SESSION)){ session_start(); }

         $sessionvar = $this->GetLoginSessionVar();
       
         if(empty($_SESSION[$sessionvar]))
         {
            return false;
         }
         return true;
    }
    function GetSelfScript()
    {
        return htmlentities($_SERVER['PHP_SELF']);
    }  
    function SafeDisplay($value_name)
    {
        if(empty($_POST[$value_name]))
        {
            return'';
        }
        return htmlentities($_POST[$value_name]);
    }
 
    function urlredirection($url)
    {
        header("Location: $url");
        exit;
    }
    function GetLoginSessionVar()
    {
        $retvar = md5($this->random_key);
        $retvar = 'usr_'.substr($retvar,0,10);
        return $retvar;
    }
 
    function query_db($username,$password)
    {
       if(!$this->databaselogincheck())
        {
            $this->HandleError("Database login failed!");
            return false;
        }        
        $username = $this->SanitizeForSQL($username);
     
        $qry = "Select * from $this->tablename where username='$username' and password='$password'";
     
        $result = mysql_query($qry,$this->connection);
     
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("Error logging in. The username or password does not match");
            return false;
        }
     
        $row = mysql_fetch_assoc($result);
        $_SESSION['name_of_user']  = $row['username'];
        $_SESSION['userid']=$row['id'];
       return true;
    }
function LogOut()
    {
        session_start();
     
        $sessionvar = $this->GetLoginSessionVar();
     
        $_SESSION[$sessionvar]=NULL;
     
        unset($_SESSION[$sessionvar]);
    }
 
    function databaselogincheck()
    {

        $this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);

        if(!$this->connection)
        {
            $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
            return false;
        }
        if(!mysql_select_db($this->database, $this->connection))
        {
            $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
            return false;
        }
        if(!mysql_query("SET NAMES 'UTF8'",$this->connection))
        {
            $this->HandleDBError('Error setting utf8 encoding');
            return false;
        }
        return true;
    }  
    function SanitizeForSQL($str)
    {
        if( function_exists( "mysql_real_escape_string" ) )
        {
              $ret_str = mysql_real_escape_string( $str );
        }
        else
        {
              $ret_str = addslashes( $str );
        }
        return $ret_str;
    }
    function Sanitize($str,$remove_nl=true)
    {
        $str = $this->StripSlashes($str);

        if($remove_nl)
        {
            $injections = array('/(\n+)/i',
                '/(\r+)/i',
                '/(\t+)/i',
                '/(%0A+)/i',
                '/(%0D+)/i',
                '/(%08+)/i',
                '/(%09+)/i'
                );
            $str = preg_replace($injections,'',$str);
        }

        return $str;
    }  
    function StripSlashes($str)
    {
        if(get_magic_quotes_gpc())
        {
            $str = stripslashes($str);
        }
        return $str;
    }  
}
?>

So,I have declared data as username,password,database,tablename,connection,random key & Error message.i have connected database using a function and each attempt while accessing the function tries to create a connection and manages connection that performs the function.

Error fun( ) :
this function is used to throw the error message to the user in case of error occurance such as Login failure,Database connection failure, and validation of the input fields of the users.

Login fun( ):
This function enables you to verify the users had already logined in the particular web browser and manage to logout if the session doesnt exist in the browser.

Query fun() :
This enables to query the Database and provides the result to the user whether it may be success or failure one.I have queried the database for username and password verification and for further implementation of sessions.

SanitizeforSQL & strip slashes & self scripting fun( ) :
I have additionally added those function for verifying the users input values and further they are stripped by removing slashes and checking your vulnerability in the input values.I have mentioned the top vulnerability of PHP in my last posts.

urlredirection ( ):
This function enables the users to redirect the page.this is mainly used in the script to redirect to home page once Your credentials and everything is correct.

GetLoginSessionVar() :
This function is mainly implemented for setting session in login with the help of randomkey ( ) funtion which generates the session to implement.I have encrypted the PHPSESSID also for well privacy experience.Session is the important concept in programming because all data is dependent on session values.so,be cautious in determining the session.

Now,It's time to connect with Database.
Let us pass the Credentials and all the regarding data's through the function call statements and creating new instance Object and maintain the data.

database_connect.php


<?PHP
require_once("./function_data_class.php");
$login_user = new login_user();
$login_user->DBinitialize(/*hostname*/'localhost',
                      /*username*/'root',
                      /*password*/'Yourpassword',
                      /*database name*/'tce',
                      /*table name*/'users');

$login_user->SetRandomKey('qSRcCS9DasrPvr');
?>
here we are passing the arguments for function to be executed.

home.php

here I have implemented function url redirection with input as url and checking the login function.


<?php
include('./database_connect.php');
if(!$login_user->CheckLogin() )
{
    $login_user->urlredirection("index.php");
    exit;
}
echo "welcome,".$_SESSION['name_of_user'];
?>

logout.php
Logout Fun ( ) enables to destroy the object to destroy and destroy the session naturally to bring the user to stop using the site.
<?PHP
require_once("./database_connect.php");
$login_user->LogOut();
?>

Index.php
I have called Check login ( ) fun, Error message fun ( ) , Selfscript fun ( ) , url redirection ( ) inorder to get a successful login.
<?PHP
require_once("./database_connect.php");
if(!$login_user->CheckLogin())
{
 }
else
{ $login_user->urlredirection("home.php");
    exit;
}  ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
      <title>mech tce</title>
<link rel="shortcut icon" href=".\S.gif" type="image/x-icon">
      <link rel="STYLESHEET" type="text/css" href="style.css">
</head>
<body style="background-color:#E7E7E7">
<?PHP
if(isset($_POST['submitted']))
{
   if($login_user->Login())
   {
        $login_user->urlredirection("home.php");
   }
}
?>
<div id='login_user' align="middle" style="margin-top:80px;">
<form id='login' action='<?php echo $login_user->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset style="background-color:#d7d7d7" >
<legend>Login</legend>

<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class='container' >
<?php if($login_user->GetErrorMessage())
{ ?>
<div class='error'><b><?php echo $login_user->GetErrorMessage(); ?></b></div>
 <?php }  ?>
    <label for='username' >Username*:</label><br/>
    <input type='text' placeholder='username here...' name='username' id='username' value='<?php echo $login_user->SafeDisplay('username') ?>' maxlength="50" /><br/>
<div class='container'>
    <label for='password'>Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" placeholder='password here...'/><br/>
  </div><div class='container'>
<input type='submit' name='Submit' value='Login' />
</div>
<div class='short_explanation'>*Required Fields</div><br/>
</fieldset>
</form>
</div>
</div>
</body>
</html>

I'm leaving the style sheet defining in Your side just i had given class name at each tag you can define it on your own.

Thats it.This can successfully create Login System for Your site and manage the functions and code efficient for later updates.Feel free to pointing out my Bugs and share.

5 comments:

naren said...

thanks for the post ! amazing ! gonna try it !

-naren

Anonymous said...

Nice but logout link is not there in home.php

shivasurya said...

just create a link that goes to logout.php
thats it completed !

Sivaprabu Ganesan said...

Hey Shiva Surya,

Please write a Article about REST (web-services in PHP).

shivasurya said...

yeah @siva i will post it soon!

Post a Comment

feel free to post your comments! Don't Spam here!