login class using MVC approach

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • semanticnotion
    New Member
    • Sep 2010
    • 66

    login class using MVC approach

    i want to make a login class using MVC approach. First my html form code is in my view folder then i want authorizing code in controller class and the query and the connection are under my model class so
    is it possible to call the method of one class into another class e.g (line no 11 in second tag correspond to line no 31 in third tag)

    html form
    Code:
    <form method="post" action="check_login.php">
    <table><tr><td>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="Username" size="10" maxlength="40"  /></td></tr>
    <tr><td>Password:&nbsp; <input type="password"  name="Password" size="10" maxlength="10"  /></td></tr>
    <tr><td><input type="submit" name="Submit" value="login" /></td></tr></table>
                        
    
    </form>

    In my controller class(check_log in.php)

    Code:
    class controller{
    private $username;
    private $password;
    function_construct();
    {
    $this->username=$_POST[Username];
    $this->password=$_POST[Password];
    
    require_once(../model/Loginsystem.php)
    $loginSystem = new LoginSystem();
    if($loginSystem->doLogin($this->username,$this->password))
    }
    }

    model class
    Code:
    class LoginSystem
    {
    	var	$db_host,
    		$db_name,
    		$db_user,
    		$db_password,
    		$connection,
    		$username,
    		$password;
    
    	/**
    	 * Constructor
    	 */
    	function LoginSystem()
    	{
    		require_once('settings.php');
    		
    		$this->db_host = $dbhost;
    		$this->db_name = $dbname;
    		$this->db_user = $dbuser;
    		$this->db_password = $dbpassword;
    	}
    	
    	
    	
    	/**
    	 * Check username and password against DB
    	 *
    	 * @return true/false
    	 */
    	function doLogin($username, $password)
    	{
    		$this->connect();
    		
    		$this->username = $username;
    		$this->password = $password;
    		
    		// check db for user and pass here.
    		$sql = sprintf("SELECT * FROM `admin` WHERE user = '$this->username' and Pass = '$this->password'",
    		$this->clean($this->username), md5($this->clean($this->password)));
    						
    		$result = mysql_query($sql, $this->connection);
    		
    		// If no user/password combo exists return false
    		if(mysql_affected_rows($this->connection) != 1)
    		{
    			$this->disconnect();
    			return false;
    		}
    		else // matching login ok
    		{
    			$row = mysql_fetch_assoc($result);
    			
    			// more secure to regenerate a new id.
    			session_regenerate_id();
    			
    			//set session vars up
    			
    			
    		}
    		
    		$this->disconnect();
    		return true;
    	}
    	
    	/**
    	 * Destroy session data/Logout.
    	 */
    	function logout()
    	{
    		unset($_SESSION['LoggedIn']);
    		unset($_SESSION['userName']);
    		session_destroy();
    	}
    	
    	/**
    	 * Connect to the Database
    	 * 
    	 * @return true/false
    	 */
    	function connect()
    	{
    		$this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL");
    		
    		mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!");
    		
    		// Valid connection object? everything ok?
    		if($this->connection)
    		{
    			return true;
    		}
    		else return false;
    	}
    	
    	/**
    	 * Disconnect from the db
    	 */
    	function disconnect()
    	{
    		mysql_close($this->connection);
    	}
  • kovik
    Recognized Expert Top Contributor
    • Jun 2007
    • 1044

    #2
    That's generally the way OOP works... What is the problem?

    Comment

    • semanticnotion
      New Member
      • Sep 2010
      • 66

      #3
      It dos't work.

      Comment

      • kovik
        Recognized Expert Top Contributor
        • Jun 2007
        • 1044

        #4
        Thank you for your detailed and insightful debugging process. I'm sure the fact that it "dos't work" is completed unrelated with the fact that you NEVER SET YOUR SESSION VARIABLES.

        Could just be me, though.

        Comment

        • semanticnotion
          New Member
          • Sep 2010
          • 66

          #5
          ok i change the code just little now i just want to call from view to controller and then from controller to model the code is bellow but still not working.

          Call from view to control in line no 18
          Code:
          
          
          <?php session_start();
          
          	require_once('../controller/check_login.php');
          
          	if(isset($_POST['Submit']))
          	{
          		if((!$_POST['Username']) || (!$_POST['Password']))
          		{
          			// display error message
          			header('location: main_login.php?msg=1');// show error
          			exit;
          		}
          
          		$loginSystem = new CheckLogin();
          		if($loginSystem->check($_POST['Username'],$_POST['Password']))
          		{
          			/**
          			 * Redirect here to your secure page
          			 */
          			header('location: index.php');
          		}
          		else
          		{
          			header('location: main_login.php?msg=2');
          			exit;
          		}
          	}
          
          	/**
          	 * show Error messages
          	 *
          	 */
          	function showMessage()
          	{
          		if(is_numeric($_GET['msg']))
          		{
          			switch($_GET['msg'])
          			{
          				case 1: echo "Please fill both fields.";
          				break;
          
          				case 2: echo "Incorrect Login Details";
          				break;
          			}
          		}
          	}
          ?>
          
                          
          <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
          <table><tr><td>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="Username" size="10" maxlength="40"  /></td></tr>
          <tr><td>Password:&nbsp; <input type="password"  name="Password" size="10" maxlength="10"  /></td></tr>
          <tr><td><input type="submit" name="Submit" value="login" /></td></tr></table>
                              
          
          </form>
          
          		</div>
          	
          
          	<div><p>&nbsp;</p></div></div></div> 
          
          
          </body>
          </html>

          Call from controller to model in line no 23


          Code:
          <?php session_start();
          require_once('../model/LoginSystem.class.php');
          	class ChechLogin
                  {
                  var $username,
                      $pass;
          
                  function isLoggedIn()
          	{
          		if($_SESSION['LoggedIn'])
          		{
          			return true;
          		}
          		else return false;
          	}
                  
                      function check($user , $pass)
                      {
                          $this->username=$user;
                          $this->pass=$pass;
          
                          $loginSystem = new LoginSystem();
          		if($loginSystem->doLogin($this->username,$this->pass))
                          {
                              session_regenerate_id();
          
          			//set session vars up
          			$_SESSION['LoggedIn'] = true;
                              $_SESSION['userName'] = $this->username;
          
                          }
                          return true;
                      }
          
          function logout()
          	{
          		unset($_SESSION['LoggedIn']);
          		unset($_SESSION['userName']);
          		session_destroy();
          	}
          
              }
          ?>
          Code:
          <?php session_start();
          
          
          
          class LoginSystem
          {
          	var	$db_host,
          		$db_name,
          		$db_user,
          		$db_password,
          		$connection,
          		$username,
          		$password;
          
          	/**
          	 * Constructor
          	 */
          	function LoginSystem()
          	{
          		require_once('settings.php');
          		
          		$this->db_host = $dbhost;
          		$this->db_name = $dbname;
          		$this->db_user = $dbuser;
          		$this->db_password = $dbpassword;
          	}
          	
          	
          	
          	/**
          	 * Check username and password against DB
          	 *
          	 * @return true/false
          	 */
          	function doLogin($username, $password)
          	{
          		$this->connect();
          		
          		$this->username = $username;
          		$this->password = $password;
          		
          		// check db for user and pass here.
          		$sql = sprintf("SELECT * FROM `admin` WHERE user = '$this->username' and Pass = '$this->password'",
          		$this->clean($this->username), md5($this->clean($this->password)));
          						
          		$result = mysql_query($sql, $this->connection);
          		
          		// If no user/password combo exists return false
          		if(mysql_affected_rows($this->connection) != 1)
          		{
          			$this->disconnect();
          			return false;
          		}
          		else // matching login ok
          		{
          			$row = mysql_fetch_assoc($result);
          			
          			// more secure to regenerate a new id.
          			//session_regenerate_id();
          			
          			//set session vars up
          			//$_SESSION['LoggedIn'] = true;
                             // $_SESSION['userName'] = $this->username;
          			
          		}
          		
          		$this->disconnect();
          		return true;
          	}
          	
          	
          	function connect()
          	{
          		$this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL");
          		
          		mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!");
          		
          		// Valid connection object? everything ok?
          		if($this->connection)
          		{
          			return true;
          		}
          		else return false;
          	}
          	
          	/**
          	 * Disconnect from the db
          	 */
          	function disconnect()
          	{
          		mysql_close($this->connection);
          	}
          	
          	/**
          	 * Cleans a string for input into a MySQL Database.
          	 * Gets rid of unwanted characters/SQL injection etc.
          	 * 
          	 * @return string
          	 */
          	function clean($str)
          	{
          		// Only remove slashes if it's already been slashed by PHP
          		if(get_magic_quotes_gpc())
          		{
          			$str = stripslashes($str);
          		}
          		// Let MySQL remove nasty characters.
          		$str = mysql_real_escape_string($str);
          		
          		return $str;
          	}
          	
          
          	
          
          }
          
          ?>

          where is problem in my code could you please help me....!

          Comment

          • kovik
            Recognized Expert Top Contributor
            • Jun 2007
            • 1044

            #6
            Once again, you haven't told us what the errors are... We're not going to write your code for you. Tell us where it's going wrong and what it should do.

            Comment

            • semanticnotion
              New Member
              • Sep 2010
              • 66

              #7
              it redirect me to main_login.php and i want to redirect to index.php (line 23 in first tag)

              Comment

              • semanticnotion
                New Member
                • Sep 2010
                • 66

                #8
                and if i remove the controller layer and put the code of check_login.php in logsystem(model ) then it works fine but i want it to pass through controller layer.

                Comment

                • kovik
                  Recognized Expert Top Contributor
                  • Jun 2007
                  • 1044

                  #9
                  1. Firstly, the Location header should be capitalized.
                  2. Secondly, you named your class "ChechLogin " but you try to create an object called "CheckLogin ".
                  3. Thirdly, "ChechLogin::ch eck()" will always return true.

                  Comment

                  • semanticnotion
                    New Member
                    • Sep 2010
                    • 66

                    #10
                    Thanks for your deep attention sir i correct the spelling of check and redirect me to index.php but nothing is displayed on that page.

                    Comment

                    • kovik
                      Recognized Expert Top Contributor
                      • Jun 2007
                      • 1044

                      #11
                      I think you need to turn on error_reporting. Then tell me what you are after and what you are getting.

                      Comment

                      • semanticnotion
                        New Member
                        • Sep 2010
                        • 66

                        #12
                        the error on index.php is



                        Warning: require(../model/check_login.php ): failed to open stream: No such file or directory in /var/www/test/view/makeSecure.php on line 14 Call Stack: 0.0005 330052 1. {main}() /var/www/test/view/index.php:0 0.0706 333796 2. require('/var/www/test/view/makeSecure.php' ) /var/www/test/view/index.php:6 Fatal error: require(): Failed opening required '../model/check_login.php ' (include_path=' .:/usr/share/php:/usr/share/pear') in /var/www/test/view/makeSecure.php on line 14 Call Stack: 0.0005 330052 1. {main}() /var/www/test/view/index.php:0 0.0706 333796 2. require('/var/www/test/view/makeSecure.php' ) /var/www/test/view/index.php:6

                        Comment

                        • kovik
                          Recognized Expert Top Contributor
                          • Jun 2007
                          • 1044

                          #13
                          So, as you can see, it's not finding the files that you are looking for. Check the paths.

                          Comment

                          • semanticnotion
                            New Member
                            • Sep 2010
                            • 66

                            #14
                            Thanks kovik it works thanks you very much the path was wrong in make secure now it works but the following error comes still.


                            otice: A session had already been started - ignoring session_start() in /var/www/test/controller/check_login.php on line 1 Call Stack: 0.0004 329732 1. {main}() /var/www/test/view/index.php:0 0.0007 333480 2. require('/var/www/test/view/makeSecure.php' ) /var/www/test/view/index.php:6 0.0015 344924 3. require('/var/www/test/controller/check_login.php ') /var/www/test/view/makeSecure.php: 14 0.0015 344968 4. session_start() /var/www/test/controller/check_login.php :1 Notice: A session had already been started - ignoring session_start() in /var/www/test/model/LoginSystem.cla ss.php on line 1 Call Stack: 0.0004 329732 1. {main}() /var/www/test/view/index.php:0 0.0007 333480 2. require('/var/www/test/view/makeSecure.php' ) /var/www/test/view/index.php:6 0.0015 344924 3. require('/var/www/test/controller/check_login.php ') /var/www/test/view/makeSecure.php: 14 0.0028 376756 4. require_once('/var/www/test/model/LoginSystem.cla ss.php') /var/www/test/controller/check_login.php :2 0.0028 376800 5. session_start() /var/www/test/model/LoginSystem.cla ss.php:1

                            Comment

                            • kovik
                              Recognized Expert Top Contributor
                              • Jun 2007
                              • 1044

                              #15
                              That means that you are calling session_start too many times. Try to only call it once.

                              Comment

                              Working...