views:

247

answers:

1

Hi

I've built a class called Login with a construct that either logs them in or it doesn't... I also have a static function called isAuthenticated which is meant to check if the user is logged in or not... I've been messing around with static functions etc but can't seem to get what I want.

Ideally, it'd be where I can easily go

<?php if (Login::isAuthenticated()) { ?>
<a href="/sign-out/">Sign Out</a>
<?php } ?>

Here is my class so far... Complete with my attempts..

class Login
 {
    private static $_auth;

    public function __construct($username, $rawPassword) {

     global $db;

     require('edit/users/config.php');

     $hashedPassword = sha1(SALT . $_POST['password']);

     $query = 'SELECT firstname FROM users WHERE user = "' . $db->cleanString($username) . '" AND pass = "' . $db->cleanString($hashedPassword) . '" LIMIT 1';


     $login = $db->query($query);

     if ($login) {


      $_SESSION['username'] = $username;
      self::$_auth = true;



      header('Location: ' . CONFIG_DIR_BASE);


     } else {

      ErrorHandler::addErrorToStack('Your username and/or password did not match one on our system. ');

     }

    }



    public static function isAuthenticated() {



      return self::$_auth;


    }







 }

Thank you very much!

+7  A: 

Since HTTP is stateless, your class' static variable ($_auth) won't 'survive' between pageloads, so if you're trying to make the variable stick, you'll need to store it as a Session variable.

However, I would strongly encourage you to not write your own auth class unless you are really serious about it. There are dozens of excellent PHP auth scripts out there to pick from, that have already addressed all the intricacies of web authentication.

Jens Roland
Good eye. Your isAuthenticated property could just check to see if the username is set. If it's not, you're not logged in. If it is, you're logged in. Just make sure to clear it once you've logged off.
Mike Christiansen
Thanks.. Think I'll use isset($_SESSION['username']) .. and I'll look into the auth classes.
alex