469,301 Members | 2,272 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,301 developers. It's quick & easy.

login class using MVC approach

semanticnotion
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
Expand|Select|Wrap|Line Numbers
  1. <form method="post" action="check_login.php">
  2. <table><tr><td>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="Username" size="10" maxlength="40"  /></td></tr>
  3. <tr><td>Password:&nbsp; <input type="password"  name="Password" size="10" maxlength="10"  /></td></tr>
  4. <tr><td><input type="submit" name="Submit" value="login" /></td></tr></table>
  5.  
  6.  
  7. </form>

In my controller class(check_login.php)

Expand|Select|Wrap|Line Numbers
  1. class controller{
  2. private $username;
  3. private $password;
  4. function_construct();
  5. {
  6. $this->username=$_POST[Username];
  7. $this->password=$_POST[Password];
  8.  
  9. require_once(../model/Loginsystem.php)
  10. $loginSystem = new LoginSystem();
  11. if($loginSystem->doLogin($this->username,$this->password))
  12. }
  13. }

model class
Expand|Select|Wrap|Line Numbers
  1. class LoginSystem
  2. {
  3.     var    $db_host,
  4.         $db_name,
  5.         $db_user,
  6.         $db_password,
  7.         $connection,
  8.         $username,
  9.         $password;
  10.  
  11.     /**
  12.      * Constructor
  13.      */
  14.     function LoginSystem()
  15.     {
  16.         require_once('settings.php');
  17.  
  18.         $this->db_host = $dbhost;
  19.         $this->db_name = $dbname;
  20.         $this->db_user = $dbuser;
  21.         $this->db_password = $dbpassword;
  22.     }
  23.  
  24.  
  25.  
  26.     /**
  27.      * Check username and password against DB
  28.      *
  29.      * @return true/false
  30.      */
  31.     function doLogin($username, $password)
  32.     {
  33.         $this->connect();
  34.  
  35.         $this->username = $username;
  36.         $this->password = $password;
  37.  
  38.         // check db for user and pass here.
  39.         $sql = sprintf("SELECT * FROM `admin` WHERE user = '$this->username' and Pass = '$this->password'",
  40.         $this->clean($this->username), md5($this->clean($this->password)));
  41.  
  42.         $result = mysql_query($sql, $this->connection);
  43.  
  44.         // If no user/password combo exists return false
  45.         if(mysql_affected_rows($this->connection) != 1)
  46.         {
  47.             $this->disconnect();
  48.             return false;
  49.         }
  50.         else // matching login ok
  51.         {
  52.             $row = mysql_fetch_assoc($result);
  53.  
  54.             // more secure to regenerate a new id.
  55.             session_regenerate_id();
  56.  
  57.             //set session vars up
  58.  
  59.  
  60.         }
  61.  
  62.         $this->disconnect();
  63.         return true;
  64.     }
  65.  
  66.     /**
  67.      * Destroy session data/Logout.
  68.      */
  69.     function logout()
  70.     {
  71.         unset($_SESSION['LoggedIn']);
  72.         unset($_SESSION['userName']);
  73.         session_destroy();
  74.     }
  75.  
  76.     /**
  77.      * Connect to the Database
  78.      * 
  79.      * @return true/false
  80.      */
  81.     function connect()
  82.     {
  83.         $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL");
  84.  
  85.         mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!");
  86.  
  87.         // Valid connection object? everything ok?
  88.         if($this->connection)
  89.         {
  90.             return true;
  91.         }
  92.         else return false;
  93.     }
  94.  
  95.     /**
  96.      * Disconnect from the db
  97.      */
  98.     function disconnect()
  99.     {
  100.         mysql_close($this->connection);
  101.     }
Oct 15 '10 #1

✓ answered by kovik

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

33 13963
kovik
1,044 Expert 1GB
That's generally the way OOP works... What is the problem?
Oct 15 '10 #2
It dos't work.
Oct 18 '10 #3
kovik
1,044 Expert 1GB
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.
Oct 18 '10 #4
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
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.  
  4. <?php session_start();
  5.  
  6.     require_once('../controller/check_login.php');
  7.  
  8.     if(isset($_POST['Submit']))
  9.     {
  10.         if((!$_POST['Username']) || (!$_POST['Password']))
  11.         {
  12.             // display error message
  13.             header('location: main_login.php?msg=1');// show error
  14.             exit;
  15.         }
  16.  
  17.         $loginSystem = new CheckLogin();
  18.         if($loginSystem->check($_POST['Username'],$_POST['Password']))
  19.         {
  20.             /**
  21.              * Redirect here to your secure page
  22.              */
  23.             header('location: index.php');
  24.         }
  25.         else
  26.         {
  27.             header('location: main_login.php?msg=2');
  28.             exit;
  29.         }
  30.     }
  31.  
  32.     /**
  33.      * show Error messages
  34.      *
  35.      */
  36.     function showMessage()
  37.     {
  38.         if(is_numeric($_GET['msg']))
  39.         {
  40.             switch($_GET['msg'])
  41.             {
  42.                 case 1: echo "Please fill both fields.";
  43.                 break;
  44.  
  45.                 case 2: echo "Incorrect Login Details";
  46.                 break;
  47.             }
  48.         }
  49.     }
  50. ?>
  51.  
  52.  
  53. <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  54. <table><tr><td>Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="Username" size="10" maxlength="40"  /></td></tr>
  55. <tr><td>Password:&nbsp; <input type="password"  name="Password" size="10" maxlength="10"  /></td></tr>
  56. <tr><td><input type="submit" name="Submit" value="login" /></td></tr></table>
  57.  
  58.  
  59. </form>
  60.  
  61.         </div>
  62.  
  63.  
  64.     <div><p>&nbsp;</p></div></div></div> 
  65.  
  66.  
  67. </body>
  68. </html>
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  

Call from controller to model in line no 23


Expand|Select|Wrap|Line Numbers
  1. <?php session_start();
  2. require_once('../model/LoginSystem.class.php');
  3.     class ChechLogin
  4.         {
  5.         var $username,
  6.             $pass;
  7.  
  8.         function isLoggedIn()
  9.     {
  10.         if($_SESSION['LoggedIn'])
  11.         {
  12.             return true;
  13.         }
  14.         else return false;
  15.     }
  16.  
  17.             function check($user , $pass)
  18.             {
  19.                 $this->username=$user;
  20.                 $this->pass=$pass;
  21.  
  22.                 $loginSystem = new LoginSystem();
  23.         if($loginSystem->doLogin($this->username,$this->pass))
  24.                 {
  25.                     session_regenerate_id();
  26.  
  27.             //set session vars up
  28.             $_SESSION['LoggedIn'] = true;
  29.                     $_SESSION['userName'] = $this->username;
  30.  
  31.                 }
  32.                 return true;
  33.             }
  34.  
  35. function logout()
  36.     {
  37.         unset($_SESSION['LoggedIn']);
  38.         unset($_SESSION['userName']);
  39.         session_destroy();
  40.     }
  41.  
  42.     }
  43. ?>
  44.  
Expand|Select|Wrap|Line Numbers
  1. <?php session_start();
  2.  
  3.  
  4.  
  5. class LoginSystem
  6. {
  7.     var    $db_host,
  8.         $db_name,
  9.         $db_user,
  10.         $db_password,
  11.         $connection,
  12.         $username,
  13.         $password;
  14.  
  15.     /**
  16.      * Constructor
  17.      */
  18.     function LoginSystem()
  19.     {
  20.         require_once('settings.php');
  21.  
  22.         $this->db_host = $dbhost;
  23.         $this->db_name = $dbname;
  24.         $this->db_user = $dbuser;
  25.         $this->db_password = $dbpassword;
  26.     }
  27.  
  28.  
  29.  
  30.     /**
  31.      * Check username and password against DB
  32.      *
  33.      * @return true/false
  34.      */
  35.     function doLogin($username, $password)
  36.     {
  37.         $this->connect();
  38.  
  39.         $this->username = $username;
  40.         $this->password = $password;
  41.  
  42.         // check db for user and pass here.
  43.         $sql = sprintf("SELECT * FROM `admin` WHERE user = '$this->username' and Pass = '$this->password'",
  44.         $this->clean($this->username), md5($this->clean($this->password)));
  45.  
  46.         $result = mysql_query($sql, $this->connection);
  47.  
  48.         // If no user/password combo exists return false
  49.         if(mysql_affected_rows($this->connection) != 1)
  50.         {
  51.             $this->disconnect();
  52.             return false;
  53.         }
  54.         else // matching login ok
  55.         {
  56.             $row = mysql_fetch_assoc($result);
  57.  
  58.             // more secure to regenerate a new id.
  59.             //session_regenerate_id();
  60.  
  61.             //set session vars up
  62.             //$_SESSION['LoggedIn'] = true;
  63.                    // $_SESSION['userName'] = $this->username;
  64.  
  65.         }
  66.  
  67.         $this->disconnect();
  68.         return true;
  69.     }
  70.  
  71.  
  72.     function connect()
  73.     {
  74.         $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL");
  75.  
  76.         mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!");
  77.  
  78.         // Valid connection object? everything ok?
  79.         if($this->connection)
  80.         {
  81.             return true;
  82.         }
  83.         else return false;
  84.     }
  85.  
  86.     /**
  87.      * Disconnect from the db
  88.      */
  89.     function disconnect()
  90.     {
  91.         mysql_close($this->connection);
  92.     }
  93.  
  94.     /**
  95.      * Cleans a string for input into a MySQL Database.
  96.      * Gets rid of unwanted characters/SQL injection etc.
  97.      * 
  98.      * @return string
  99.      */
  100.     function clean($str)
  101.     {
  102.         // Only remove slashes if it's already been slashed by PHP
  103.         if(get_magic_quotes_gpc())
  104.         {
  105.             $str = stripslashes($str);
  106.         }
  107.         // Let MySQL remove nasty characters.
  108.         $str = mysql_real_escape_string($str);
  109.  
  110.         return $str;
  111.     }
  112.  
  113.  
  114.  
  115.  
  116. }
  117.  
  118. ?>
  119.  

where is problem in my code could you please help me....!
Oct 19 '10 #5
kovik
1,044 Expert 1GB
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.
Oct 19 '10 #6
it redirect me to main_login.php and i want to redirect to index.php (line 23 in first tag)
Oct 19 '10 #7
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.
Oct 19 '10 #8
kovik
1,044 Expert 1GB
  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::check()" will always return true.
Oct 19 '10 #9
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.
Oct 19 '10 #10
kovik
1,044 Expert 1GB
I think you need to turn on error_reporting. Then tell me what you are after and what you are getting.
Oct 19 '10 #11
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
Oct 19 '10 #12
kovik
1,044 Expert 1GB
So, as you can see, it's not finding the files that you are looking for. Check the paths.
Oct 19 '10 #13
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.class.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.class.php') /var/www/test/controller/check_login.php:2 0.0028 376800 5. session_start() /var/www/test/model/LoginSystem.class.php:1
Oct 19 '10 #14
kovik
1,044 Expert 1GB
That means that you are calling session_start too many times. Try to only call it once.
Oct 19 '10 #15
Ooh thats great...!
It works fine Thanks kovik thanks very much if you are on my back i will be the php master soon.
hope you will help me in future.
Oct 19 '10 #16
kovik
1,044 Expert 1GB
No problem. :)
Oct 19 '10 #17
ok kovik if i want to retrieve the data in html table from admin e.g

ID NAME PASSWORD
1 abc *******

then how can i call this from view to controller and from controller to model remember that the select query should be in model class and data will be displayed on html page in view class.
Oct 21 '10 #18
kovik
1,044 Expert 1GB
The way that MVC works is that your Controller decides which Model to use and which View to use, based on user input. On the internet, "user input" is generally simplified down to the selected URL.

The Controller chooses the model which has the data it needs, and it choses the View that displays that data the way it needs to be displayed. Then, it injects the data into the view and outputs the result.

You'd want a Model class that creates an array of data from the database data, and a View class that uses that data to make your HTML table.
Oct 21 '10 #19
i do this in my html

Expand|Select|Wrap|Line Numbers
  1. $rs=new SelectSubject();
  2.  
  3. $select=$rs->get();
  4.  
  5.  //$select=mysql_query("select * from subject") or die(mysql_error());
  6.  
  7.  
  8.  
  9. while($rs=mysql_fetch_array($select))
  10. {
then in controller like this

Expand|Select|Wrap|Line Numbers
  1.  class SelectSubject
  2.     {
  3.         function get()
  4.         {
  5.             $selectsubject=new LoginSystem();
  6.  
  7.             $selectsubject->getSubject();
  8.         }
  9.  
and in model

Expand|Select|Wrap|Line Numbers
  1. function getSubject()
  2.     {
  3.         $this->connect();
  4.         $sql=sprintf("select * from subject") or die(mysql_error());
  5.         $result=mysql_query($sql);
  6.         return $result;
  7.     }

this give me the error
Expand|Select|Wrap|Line Numbers
  1. Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /var/www/test/view/add_subject.php on line 112 Call Stack: 0.0007 338948 1. {main}() /var/www/test/view/add_subject.php:0 0.0215 397500 2. mysql_fetch_array() /var/www/test/view/add_subject.php:112

code of line 112 is
Expand|Select|Wrap|Line Numbers
  1. while($rs=mysql_fetch_array($select))
Oct 21 '10 #20
kovik
1,044 Expert 1GB
That just means that $select is not a resource. You can verify this by echoing get_type(). If it's not a result, then you are probably getting a MySQL error. However, you don't handle it correctly.

This:
Expand|Select|Wrap|Line Numbers
  1. $sql=sprintf("select * from subject") or die(mysql_error());
  2. $result=mysql_query($sql);
Should be this:
Expand|Select|Wrap|Line Numbers
  1. $sql=sprintf("select * from subject");
  2. $result=mysql_query($sql)or die(mysql_error());
Also, the call to sprintf() is unnecessary.
Oct 21 '10 #21
kovik i do the changes but still not working is there any other possibility to call from to controller and then model but the data should be displayed in view and query should be in model.
Oct 22 '10 #22
kovik
1,044 Expert 1GB
What errors are you getting?
Oct 22 '10 #23
there is no error but the data is not displayed in html table.
insert query is working fine but select does't work
i change the code but still not working plz help whats wrong with this code.
Oct 25 '10 #24
Notice: Undefined variable: dbhost in /var/www/test/model/LoginSystem.class.php on line 31 Call Stack: 0.0006 341820 1. {main}() /var/www/test/view/add_subject.php:0 0.1268 402776 2. SelectSubject->get() /var/www/test/view/add_subject.php:105 0.1268 403536 3. LoginSystem->LoginSystem() /var/www/test/controller/check_login.php:75 Notice: Undefined variable: dbname in /var/www/test/model/LoginSystem.class.php on line 32 Call Stack: 0.0006 341820 1. {main}() /var/www/test/view/add_subject.php:0 0.1268 402776 2. SelectSubject->get() /var/www/test/view/add_subject.php:105 0.1268 403536 3. LoginSystem->LoginSystem() /var/www/test/controller/check_login.php:75 Notice: Undefined variable: dbuser in /var/www/test/model/LoginSystem.class.php on line 33 Call Stack: 0.0006 341820 1. {main}() /var/www/test/view/add_subject.php:0 0.1268 402776 2. SelectSubject->get() /var/www/test/view/add_subject.php:105 0.1268 403536 3. LoginSystem->LoginSystem() /var/www/test/controller/check_login.php:75 Notice: Undefined variable: dbpassword in /var/www/test/model/LoginSystem.class.php on line 34 Call Stack: 0.0006 341820 1. {main}() /var/www/test/view/add_subject.php:0 0.1268 402776 2. SelectSubject->get() /var/www/test/view/add_subject.php:105 0.1268 403536 3. LoginSystem->LoginSystem() /var/www/test/controller/check_login.php:75 Warning: mysql_connect(): Access denied for user 'www-data'@'localhost' (using password: NO) in /var/www/test/model/LoginSystem.class.php on line 91 Call Stack: 0.0006 341820 1. {main}() /var/www/test/view/add_subject.php:0 0.1268 402776 2. SelectSubject->get() /var/www/test/view/add_subject.php:105 0.1287 403536 3. LoginSystem->getSubject() /var/www/test/controller/check_login.php:77 0.1287 403536 4. LoginSystem->connect() /var/www/test/model/LoginSystem.class.php:180 0.1287 403712 5. mysql_connect() /var/www/test/model/LoginSystem.class.php:91 Unable to connect to MySQL
Oct 25 '10 #25
3 days ago it gives me the error of not valid resource and now its give me the above error
Oct 25 '10 #26
kovik
1,044 Expert 1GB
The error says "Undefined variable: dbhost". The only time that you reference "$dbhost" is in your constructor for the LoginSystem class. It is never defined. Did you mean to include it in your constructor's declaration?

Instead of:
Expand|Select|Wrap|Line Numbers
  1. function LoginSystem()
  2.     {
  3.         require_once('settings.php');
  4.  
  5.         $this->db_host = $dbhost;
  6.         $this->db_name = $dbname;
  7.         $this->db_user = $dbuser;
  8.         $this->db_password = $dbpassword;
  9.     }
Try:
Expand|Select|Wrap|Line Numbers
  1. function LoginSystem($dbhost, $dbname, $dbuser, $dbpassword)
  2.     {
  3.         require_once('settings.php');
  4.  
  5.         $this->db_host = $dbhost;
  6.         $this->db_name = $dbname;
  7.         $this->db_user = $dbuser;
  8.         $this->db_password = $dbpassword;
  9.     }
And be sure to send this variables when creating instances of the class. If those are supposed to be defined in "settings.php", then I'd say that this is a fairly bad design, but eh.
Oct 25 '10 #27
ya my setting.php contain "localhost","user","password","db_name" i comment that and give variable values in loginsystem class.
now
Unable to connect to MySQL
Oct 25 '10 #28
i changed the constructor like this
Expand|Select|Wrap|Line Numbers
  1.  function LoginSystem()
  2.     {
  3.         //require_once('settings.php');
  4.  
  5.         $this->db_host ="localhost";                            //$dbhost;
  6.         $this->db_name = "kims";                                //$dbname;
  7.         $this->db_user = "root";                                //$dbuser;
  8.         $this->db_password = "root";                            //$dbpassword;
  9.     }
  10.  
and it gives me no error but still data is not displayed in html table i thing i return something wrong in my controller and model.
Oct 25 '10 #29
kovik
1,044 Expert 1GB
Have you tried connecting directly using those credentials? They are likely incorrect if you can't connect.
Oct 25 '10 #30
ya its correct the user is login successfully and the data can be inserted into the table but the only problem is to retrieve that data from database table.
Oct 26 '10 #31
kovik
1,044 Expert 1GB
If your error is "Unable to connect to MySQL", then that means that your connection is not being made. Unless you have a different error, that's the only explanation.

Check here for more options.
Oct 26 '10 #32
hi all....i want to ask that you hav included setting.php under function loginSystem....but you never created file setting.php
May 28 '15 #33
Atli
5,058 Expert 4TB
It's not shown there, but it obviously exists. You generally don't include all your code when asking questions on forums, just what is relevant.
May 29 '15 #34

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by mudgilgaurav | last post: by
4 posts views Thread by John Devlon | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.