[PHP] Gebruikerssysteem class

[]
Een class voor het in/uitloggen van leden, het registreren, wachtwoord vergeten etc.
Dit is een gebruikersclass geschreven door mij, een tijdje terug alweer :P
de code spreekt redelijk voor zich, maar je kan bijv. $debug aanzetten om te zien welke functies worden aangeroepen (met de tijd erbij) of processtime om als de class 'klaar' is, de tijd te weergeven die het koste om gebruikt te worden.

Je hebt een aangepaste config.php nodig, omdat ik een count functie in de PDO class wou hebben:

database tabellen, + 2 gebruikers (ww's staan in test.php)

CREATE TABLE IF NOT EXISTS `sessions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `remember` tinyint(2) NOT NULL,
  `userid` int(11) NOT NULL,
  `random` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL DEFAULT '',
  `realname` varchar(255) NOT NULL,
  `ip` varchar(255) NOT NULL DEFAULT '',
  `useragent` varchar(255) NOT NULL,
  `logintime` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='Sessions voor de loginclass' AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `gebruikers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL DEFAULT '',
  `password` varchar(255) NOT NULL DEFAULT '',
  `email` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `enabled` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='Gebruikers voor de loginclass' AUTO_INCREMENT=4 ;

--
-- Gegevens worden uitgevoerd voor tabel `gebruikers`
--

INSERT INTO `gebruikers` (`id`, `username`, `password`, `email`, `name`, `enabled`) VALUES
(1, 'thumb', 'aa9662e6c8eff47840338596a57c1c2c2d08f38d78dc664cac0e0bdf6ae7012b', 'thumbnail95@gmail.com', 'Thumbnail 1995', 'lulzc0de'),
(2, 'testuser', 'a5529fa541dd5f7fb847204ed7381c9ecfa549849c87f787d23ca8268ca20bff', 'judojeroen@hotmdail.com', 'Test user', '1');


config.php

session_start();
$cfg['host'] = 'localhost';
$cfg['port'] = 3307;
$cfg['database'] = '****';
$cfg['username'] = '****';
$cfg['password'] = '****';

class db extends PDO
{
/**
* Function to count rows in a table
*
* @access public
* @param string $sql a sql query
* @return integer number of rows
*/
public function count($sql)
{
$sql = $this->query($sql);
$i = 0;
foreach($sql as $row){ $i ++; }
return $i;
}
}

$db = new db("mysql:host=" . $cfg['host'] . ";port=" . $cfg['port'] . ";dbname=" . $cfg['database'], $cfg['username'], $cfg['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
unset($cfg);
?>


zoals je ziet wordt gebruik gemaakt van PDO.

de errors worden als exception ge'throwed, wat je bijv. kan doen is de errors zelf aanpassen naar een error_code, dus ipv "user already enabeled or wrong code" => "WRONG_AUTH_CODE"
en als die dan ge'catched wordt, kan je er in bijv. een ini bestand zelf een error aan koppelen, en die dan 'vinden'...
als ik tijd heb na mijn examens zal ik hier wel een voorbeeld van geven

met test.php kan je het inloggen testen, en op secret.php kan je alleen komen als je bent ingelogt.

test.php

include('include/config.inc.php');
include('include/member.class.php');
try
{

$persoon = new member($db);

if(isset($_GET['logout']))
{
if($persoon->logout())
{
echo 'succesvol uitgelogd
' . PHP_EOL;
echo 'Opnieuw inloggen
' . PHP_EOL;
}
}
elseif(isset($_GET['code']) && isset($_GET['email']))
{
if($persoon->enableUser($_GET['code'], $_GET['email']))
{
echo 'succesvol geactiveerd';
}
}
else {
if($persoon->isLoggedIn())
{
echo 'Ga naar secret.php';
}
else {
if(isset($_GET['thumb']))
{
$username = 'thumb';
$password = 'test';
$remember = true;
}
elseif(isset($_GET['testuser'])) {
$username = 'testuser';
$password = 'lolzlald';
$remember = false;
}

if(isset($username) && isset($password))
{
if($persoon->login($username, $password, $remember))
{
echo 'ingelogd, refresh om nieuwe data te zien en alles';
}
} else {
echo 'Kies een gebruiker:
';
echo 'testuser
';
echo 'thumb
';
}
}
}
}
catch(Exception $e) {
echo 'error: ' . $e->getMessage() . '
' . PHP_EOL;
}
?>


secret.php
include('include/config.inc.php');
include('include/member.class.php');
try
{
$persoon = new member($db);
if($persoon->isLoggedIn())
{
echo $persoon->info('realname') . ' is ingelogd als ' . $persoon->info('username') . ' Uitloggen
' . PHP_EOL;;
if($persoon->info('remember') == 'true'){ echo 'U wordt onthouden'; }
}
else {
echo 'GEHEIM!';
}
}
catch(Exception $e) {
echo 'error: ' . $e->getMessage() . '
' . PHP_EOL;
}
?>


graag verbeteringen etc. aangeven, ik wil er graag van leren :)

voor vragen kan je reageren, of mij pm'en.

/**
 * A Member class
 *
 * a class to manage members, register,
 * login forgot password options etc.
 * this class checks the sessions with a
 * database, so they are basically hack-proof.
 *
 * @package Member
 * @author Jeroen de Jong
 * @link http://www.jeroendejong.net/
 * @copyright Copyright (c) 2011, Jeroen de Jong
 * @version 0.1.0
 */

class member
{

/**
* $db object contains the pdo object
* $salt string the salt for the password
* $startTime integer if $processTime is enabled, this will contain the startTime of the page.
* $prefix string a prefix so it doesn't affect other scripts (changable).
* $userTable string the table name where all the users are in
* $sesTable string the table where the sessions will be stored in
* $debug boolean  true to enable debugmode, false to disable
* $processTime boolean true to enable an echo of the time it took to process the page.
* $userInfo array contains info about the user
*/
static $db;
private $salt;
private $startTime;
private $prefix = "MC_";
private $userTable = "gebruikers";
private $sesTable = "sessions";
private $debug = false;
private $processTime = true;
private $userInfo = array();

/**
* Initialise class and copies
*  connection to the class
*
* @access private
* @param object $dbConnection  a PDO object
*/
function __construct($dbConnection)
{
//if the processTime is enabled, put the microtime in the startTime string
if($this->processTime == true){ $this->startTime = microtime(); }

if($this->debug == true){ echo '__construct gestart;
' . PHP_EOL; }

//check if the connection is an object
if(is_object($dbConnection))
{
//copy connection to class
$this->db = $dbConnection;

//get the salt for the passwords
$this->getSalt();

//look if there are sessions in the database.
$this->dbSessions();

}
else {
//the connection isn't a connection,
            throw new Exception('No database connection aviable');
//throw an exception and shut down
            exit;
}
}

/**
* Checking if there are sessions stored in the database
* that aren't "real" sessions anymore
*
* @access private
* @return boolean
*/
private function dbSessions()
{
if($this->debug == true){ echo 'dbSessions() gestart;
' . PHP_EOL; }

if(!$this->isLoggedIn())
{
//there are no known sessions,
//check the database anyway
$sqlQuery = "SELECT
*
FROM
`" . $this->sesTable . "`
WHERE
`ip` = " . $this->db->quote($_SERVER['REMOTE_ADDR']) . "
AND
`useragent` = " . $this->db->quote($_SERVER['HTTP_USER_AGENT']) . "
LIMIT
1";
$sql = $this->db->count($sqlQuery);

if($sql > 0)
{
//there are sessions in the database
//so loop the db's just like a login.
$sql = $this->db->query($sqlQuery);
foreach($sql as $row)
{
if($row['remember'] == 1)
{ //user wanted to be remembered

//get the user from the database
$sqlUser = $this->db->query("SELECT
*
FROM
`" . $this->userTable . "`
WHERE
`username` = " . $this->db->quote($row['username']) . "
LIMIT
1");
foreach($sqlUser as $userRow)
{
$this->userInfo['password'] = $userRow['password'];
$this->userInfo['email'] = $userRow['email'];
$_SESSION[$this->prefix . 'email'] = $userRow['email'];
}

//inserting into the userInfo
$this->userInfo['userid'] = $row['userid'];
$this->userInfo['username'] = $row['username'];
$this->userInfo['realname'] = $row['realname'];
$this->userInfo['random'] = $row['random'];
$this->userInfo['remember'] = $row['remember'];

//inserting into sessions
$_SESSION[$this->prefix . 'remember'] = $row['remember'];
$_SESSION[$this->prefix . 'ip'] = $row['ip'];
$_SESSION[$this->prefix . 'logintime'] = $row['logintime'];
$_SESSION[$this->prefix . 'useragent'] = $row['useragent'];
$_SESSION[$this->prefix . 'userid'] = $row['userid'];
$_SESSION[$this->prefix . 'username'] = $row['username'];
$_SESSION[$this->prefix . 'realname'] = $row['realname'];
$_SESSION[$this->prefix . 'random'] = $row['random'];

return true;
}
else {
//user doesn't want to be remembered, but is still in the database
//so log him out
$this->logout();
return false;
}
}
}
else {
//there aren't any sessions
return false;
}
}
else {
//sessions are still alive
return true;
}
}

/**
* Enabling a useraccount
*
* @access public
* @param string $code contains 'unlock' code
* @param string $email the e-mail adress of the user
* @return boolean
*/
public function enableUser($code, $email)
{
if($this->debug == true){ echo 'enableUser(' . $code . ', ' . $email . ') gestart;
' . PHP_EOL; }

//check if the user is logged in
if(!$this->isLoggedIn())
{

//check if the email is in the database
$sql = $this->db->count("SELECT
`id`
FROM
`" . $this->userTable . "`
WHERE
`email` = " . $this->db->quote($email));

if($sql > 0)
{
//email found, check if the code and the email adres matches the database
$sql = $this->db->count("SELECT
`id`
FROM
`" . $this->userTable . "`
WHERE
`email` = " . $this->db->quote($email) . "
AND
`enabled` = " . $this->db->quote($code));
if($sql > 0)
{

//code and email are both in the database, enable the user in an update query
$sql = $this->db->query("UPDATE
`" . $this->userTable . "`
SET
`enabled` = '1'
WHERE
`email` = " . $this->db->quote($email));
if($sql)
{
return true;
}
else {
throw new Exception('Updating user table failed');
return false;
}
}
else {
throw new Exception('user already enabeled or wrong code');
return false;
}
}
else {
throw new Exception('Unknown email adres');
return false;
}
}
else {
throw new Exception('You can\'t enable someone if you\'re already logged in');
return false;
}
}

/**
* Registering a user
*
* @access public
* @param array $regData contains the data about the user
* @return boolean
*/
public function register($regData)
{
if($this->debug == true){ echo 'register('; var_dump($regData); echo ') gestart;
' . PHP_EOL; }

//check if the regData is an array
if(is_array($regData))
{

//check if all the information is given
if(count($regData) == 4 &&
isset($regData['username']) &&
isset($regData['password']) &&
isset($regData['email']) &&
isset($regData['realname']))
{
//prepairing the given array for the insert
$username = $this->db->quote($regData['username']);
$password = $this->db->quote($this->hashPassword($regData['password']));
$email = $this->db->quote($regData['email']);
$realname = $this->db->quote($regData['realname']);

//check if the username is taken
$sql = $this->db->count("SELECT
`id`
FROM
`" . $this->userTable . "`
WHERE
`username` = " . $username);

if($sql == 0)
{
//check if the email account is used before
$sql = $this->db->count("SELECT
`id`
FROM
`" . $this->userTable . "`
WHERE
`email` = " . $email);

if($sql == 0)
{
//generate enablestring.
$enableString = substr($this->randomString(), 0, 6);

//let's put it in the database
$sql = $this->db->query("INSERT INTO
`" . $this->userTable . "`
(`username`,
`password`,
`email`,
`name`,
`enabled`)
VALUES
(" . $username . ",
" . $password . ",
" . $email . ",
" . $realname . ",
" . $this->db->quote($enableString) . ")");
if($sql)
{
if(mailUser($regData['email'], '[register] Welcome', 'this is your activation code: ' . $enableString . ', Have fun on the website'))
{
return true;
}
else {
throw new Exception('user is inserted, but mailing failed. Ask the owner of this site to enable your account');
return false;
}
}
else {
throw new Exception('Inserting new user into database failed');
return false;
}
}
else {
throw new Exception('This email adres is already registred');
return false;
}
}
else {
throw new Exception('Username already taken');
return false;
}
}
else {
throw new Exception('There should be 4 keys (username, password, email and realname as key)');
return false;
}
}
else {
throw new Exception('The parameter should be an array');
return false;
}
}

/**
* Logging in the user
*
* @access public
* @param string $username username
* @param string $password raw password (no hashes or anything)
* @param boolean $remember 'remember me' function, if true the sessions in the
* database will be used if the origional sessions
* aren't alive anymore.
* @return boolean
*/
public function login($username, $password, $remember)
{
if($this->debug == true){ echo 'login(' . $username . ', ' . $password . ', ' . $remember . ') gestart;
' . PHP_EOL; }

if(!$this->isLoggedIn())
{
//the user isn't already logged in

//making username and password ready for the database
$username = $this->db->quote($username);
$password = $this->db->quote($this->hashPassword($password));
if($remember == true){ $remember = 1; } else { $remember = 0; }

//put all the userinfo into the userInfo array
if($this->getUserInfo($username, $password, $remember))
{

//check if the user is enabled
if($this->isEnabledUser($username))
{
//the user is logged in correctly, all the info
//is going to be set in a database and sessions
if($this->makeSession())
{
return true;
}
else {
throw new Exception('There was an error while making the session');
return false;
}
}
else {
//he didn't activate his account
throw new Exception('You haven\'t activated your account yet.');
return false;
}
}
}
else {
//user allready logged in
throw new Exception('You\'re already logged in');
return false;
}
}

/**
* Function to mail a user for mail layout,
*  and easy editing of the contents etc.
*
* @access private
* @param string $email the users mail
* @param string $name the (user)name of the person
* @param string $subject the subject of the email
* @param string $content the content the email should have
* @return boolean
*/

private function mailUser($email, $name, $subject, $content)
{
if($this->debug == true){ echo 'mailUser(' . $email . ', ' . $name . ', ' . $subject . ', ' . $content . ') started;
' . PHP_EOL; }

$message = 'Dear ' . htmlspecialchars($email) . '
' . PHP_EOL;
$message .= $content . '
' . PHP_EOL . '
' . PHP_EOL;
$message .= '---------------------------
' . PHP_EOL;
$message .= 'Greetings
' . PHP_EOL;
$message .= 'Jeroen de Jong
' . PHP_EOL;

if(mail($email, '[JdJ] ' . $subject, $message))
{
return true;
}
else {
//disabled because it is moslty in an else-if construction
//throw new Exception('Error while mailing');
return false;
}
}

/**
* Password forgotten function, mails a new password to the user
*
* @access public
* @param string $email the users email
* @return boolean
*/
public function forgotPass($email)
{
if($this->debug == true){ echo 'forgotPass(' . $email . ') started;
' . PHP_EOL; }

//check if the user is logged in
if(!$this->isLoggedIn())
{

$query = "SELECT
*
FROM
`" . $this->userTable . "`
WHERE
`email` = " . $this->db->quote($email) . "
LIMIT
1";

$sql = $this->db->count($query);

//check if the email is right
if($sql > 0)
{

foreach($this->db->query($query) as $row){
//generate a randon password using the randomString function
$newPass = substr($this->randomString(), 0, md_rand(5, 8));

$sql = $this->db->query("UPDATE
`" . $this->userTable . "`
SET
`password` = " . $this->db->quote($this->hashPassword($newPass)) . "
WHERE
`email` = " . $this->db->quote($email));
//update the password with the new one
if($sql)
{
if(mailUser($regData['email'], $row['realname'], 'Your password is changed', 'This is your new password: ' . $newPass))
{
return true;
}
else {
throw new Exception('The password is changed, but the mailing failed.');
return false;
}
}
else {
throw new Exception('An error accured when changing the password');
return false;
}
}
}
else {
throw new Exception('Unknown email adres');
return false;
}
}
else {
throw new Exception('You\'re logged in, so you can\'t use this function');
return false;
}
}

/**
* Make the session en put info in the db
*
* @access private
* @return boolean
*/
private function makeSession()
{
if($this->debug == true){ echo 'makeSession() started;
' . PHP_EOL; }

$sql = $this->db->count("SELECT
*
FROM
`" . $this->userTable . "`
WHERE
`username` = " . $this->db->quote($this->userInfo['username']) . "
AND
`password` = " . $this->db->quote($this->userInfo['password']));

if($sql > 0)
{
$sqlInsert = $this->db->query("INSERT INTO
`" . $this->sesTable . "`
(`userid`,
`username`,
`remember`,
`random`,
`ip`,
`useragent`,
`logintime`,
`realname`)
VALUES(
" . $this->db->quote($this->userInfo['userid']) . ",
" . $this->db->quote($this->userInfo['username']) . ",
" . $this->db->quote($this->userInfo['remember']) . ",
" . $this->db->quote($this->userInfo['random']) . ",
" . $this->db->quote($_SERVER['REMOTE_ADDR']) . ",
" . $this->db->quote($_SERVER['HTTP_USER_AGENT']) . ",
" . time() . ",
" . $this->db->quote($this->userInfo['realname']) . "
)");
if($sqlInsert)
{
$_SESSION[$this->prefix . 'userid'] = $this->userInfo['userid'];
$_SESSION[$this->prefix . 'username'] = $this->userInfo['username'];
$_SESSION[$this->prefix . 'useragent'] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION[$this->prefix . 'ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION[$this->prefix . 'logintime'] = time();
$_SESSION[$this->prefix . 'random'] = $this->userInfo['random'];
$_SESSION[$this->prefix . 'realname'] = $this->userInfo['realname'];
$_SESSION[$this->prefix . 'remember'] = $this->userInfo['remember'];

return true;
}
else {
throw new Exception('Sessions couldn\'t be created');
return false;
}
}
}

/**
* Get the salt key or make one if doesn't exists
*
* @access private
*/
    private function getSalt()
{
if($this->debug == true){ echo 'getSalt() started;
' . PHP_EOL; }

//check if the file exists and if its readable
if(is_file("salt.key") && is_readable("salt.key"))
{
//open the file
$file =  fopen('salt.key', 'r');
//read it, and put it in the salt function
$this->salt = fread($file, 40);
//clos the file
fclose($file);
}
else {
//the file doesn't exist, or isn't readable, so
//open it with w+ (create if doesn't exist)

$file = fopen('salt.key', 'w+');
//range with the alfabeth (capital and non-capital)
$range = range('A', 'z');
//shuffle that array
shuffle($range);

//convert the array to string with implode,
//and then hash it using sha256 algoritm.
$salt = hash('sha256', implode('', $range));
//write the salt to the file
fwrite($file, $salt);
//chmod the file so we can open it later on
chmod('salt.key', 660);
//recall this method to get the salt anyway
$this->getSalt();
}
}

/**
* get info from the user
*
* @access public
* @param string $key  the key in the userInfo sessions
* @return string or boolean on failure
*/
public function info($key)
{
if($this->debug == true){ echo 'info(' . $key . ') started;
' . PHP_EOL; }

if($this->isLoggedIn())
{
if(isset($_SESSION[$this->prefix . $key]) && $key != 'random')
{
if($key == 'remember')
{
//if it is the remember session
//change 1 to true, and 0 to false
if($_SESSION[$this->prefix . $key] == 1)
{
//return as string, not as boolean.
return 'true';
}
elseif($_SESSION[$this->prefix . $key] == 0) {
return 'false';
}
}

//it exists and it isn't the random info,
//htmlspecialchar it (xss proof) and return it
return htmlspecialchars($_SESSION[$this->prefix . $key]);

}
elseif($key == 'random')
{
//another error if there was requested an random key;
throw new Exception('You can\'t acces the random key because it is private');
return false;
}
else {
throw new Exception('This key is unknown (' . htmlspecialchars($key) . ')');
return false;
}
}
else {
//nobody is logged in
throw new Exception('Nobody is logged in so there isn\'t any data');
return false;
}
}

/**
* Give a random string wich is linked to the session.
*
* @access private
* @return string
*/
private function randomString()
{
if($this->debug == true){ echo 'randomString() started;
' . PHP_EOL; }

//generate a random string dependin on the date and the microtime,
//length between 30 and 18 chars.
return substr(hash('sha256', substr(microtime(), mt_rand(1,4), mt_rand(7,10)) . md5(date('d-m-y'))), mt_rand(0, 6), mt_rand(24, 30));
}

/**
* hash the password with a salt
*
* @access private
* @param string $password  password that has to be hashed and salted
* @return string
*/
private function hashPassword($password)
{
if($this->debug == true){ echo 'hashPassword() started;
' . PHP_EOL; }

if(isset($this->salt) && !empty($this->salt))
{
//the salt will be in the middle of the password
return hash('sha256', (substr($password, 0, round(strlen($password)/2)) . $this->salt . (substr($password, round(strlen($password)/2), strlen($password)))));
}
else {
//the salt hasn't been catched/created yet.
throw new Exception('the salt hasn\'t been catched/created yet');
return false;

/*
//create or get the salt, and recall this function.
$this->getSalt();
$this->hashPassword($password);
*/
}
}

/**
* Check if the user is logged in
*
* @access public
* @return boolean
*/
public function isLoggedIn()
{
if($this->debug == true){ echo 'isLoggedIn() started;
' . PHP_EOL; }

if(isset($_SESSION[$this->prefix . 'userid']))
{
if($this->validateSession())
{
//the user is logged in, and the info is correct
return true;
}
else {
//incorrect information in the session
return false;
}
}
else {
//user isn't logged in
return false;
}
}

/**
* Checks wheter the session is valid or not.
*
* @access private
* @return boolean
*/
private function validateSession()
{
if($this->debug == true){ echo 'validateSession() started;
' . PHP_EOL; }

if(isset($_SESSION[$this->prefix . 'userid']))
{
if($_SESSION[$this->prefix . 'useragent'] == $_SERVER['HTTP_USER_AGENT'] && $_SESSION[$this->prefix . 'ip'] == $_SERVER['REMOTE_ADDR'])
{

$sql = $this->db->count("SELECT
*
FROM
`" . $this->sesTable . "`
WHERE
`userid` = " . $this->db->quote($_SESSION[$this->prefix . 'userid']) . "
AND
`username` = " . $this->db->quote($_SESSION[$this->prefix . 'username']) . "
AND
`ip` = " . $this->db->quote($_SERVER['REMOTE_ADDR']) . "
AND
`useragent` = " . $this->db->quote($_SESSION[$this->prefix . 'useragent']) . "
AND
LOWER(`random`) = LOWER(" . $this->db->quote($_SESSION[$this->prefix . 'random']) . ")
AND
LOWER(`realname`) = LOWER(" . $this->db->quote($_SESSION[$this->prefix . 'realname']) . ")");

if($sql > 0)
{
//sessions and database are simular
return true;
}
else {
$this->logout();
throw new Exception('Sessions don\'t match the database.');
return false;
}
}
else {
//false data so logout
$this->logout();
throw new Exception('Useragent or IP doesn\'t match (' . $_SESSION[$this->prefix . 'ip'] . ' != ' . $_SERVER['REMOTE_ADDR'] . ')');
return false;
}
}
else {
//there is no session...
throw new Exception('No session to validate');
return false;
}
}

/**
* Function to check if the user is enabled
*
* @access public
* @param string $username the username to check
* @return boolean
*/
public function isEnabledUser($username)
{
if($this->debug == true){ echo 'isEnabledUser(' . $username . ') started;
' . PHP_EOL; }

//query to check wheter the user is enabled or not
$sql = $this->db->count("SELECT
*
FROM
`" . $this->userTable . "`
WHERE
LOWER(`username`) = " . strtolower($username) . "
AND
`enabled` = 1
LIMIT
1");

if($sql > 0)
{
return true;
}
else {
return false;
}
}

/**
* function to get info from the database
*
* @access private
* @param string $username  prepaired username
* @param string $password  prepaired and hashed password
* @return  boolean
*/
private function getUserInfo($username, $password, $remember)
{
if($this->debug == true){ echo 'getUserInfo(' . $username . ', ' . $password . ', ' . $remember . ') started;
' . PHP_EOL; }

//query in a string so it can be used twice
$sqlQuery = "SELECT
*
FROM
`" . $this->userTable . "`
WHERE
LOWER(`username`) = " . strtolower($username) . "
AND
`password` = " . $password . "
LIMIT
1";

$sql = $this->db->count($sqlQuery);

//check if there's a account found
if($sql > 0)
{
$sql = $this->db->query($sqlQuery);

//got one! put it in the userInfo array
foreach($sql as $row)
{
$this->userInfo['userid'] = $row['id'];
$this->userInfo['username'] = $row['username'];
$this->userInfo['realname'] = $row['name'];
$this->userInfo['email'] = $row['email'];
$this->userInfo['password'] = $row['password'];
//add a random string to the userinfo
$this->userInfo['random'] = $this->randomString();
$this->userInfo['remember'] = $remember;
}

return true;
}
else {
//most likely the combination is wrong.
throw new Exception('Wrong combination');
return false;
}
}

/**
* function to log the user out
*
* @access public
* @return  boolean
*/
public function logout()
{
if($this->debug == true){ echo 'logout() started;
' . PHP_EOL; }

// Check for information that corresponds with the database and sessioninfo etc.
if(isset($_SESSION[$this->prefix . 'random']))
{
$sqlDel = $this->db->query("DELETE FROM
`" . $this->sesTable . "`
WHERE
`random` = " . $this->db->quote($_SESSION[$this->prefix . 'random']));
}
elseif(isset($_SESSION[$this->prefix . 'userid']))
{
$sqlDel = $this->db->query("DELETE FROM
`" . $this->sesTable . "`
WHERE
`userid` = " . $this->db->quote($_SESSION[$this->prefix . 'userid']));
}
elseif(isset($_SERVER['REMOTE_ADDR']))
{
$sqlDel = $this->db->query("DELETE FROM
`" . $this->sesTable . "`
WHERE
`ip` = " . $this->db->quote($_SERVER['REMOTE_ADDR']));
}

//unsetting each session individually,
//so it doesn't affect other scripts
unset($_SESSION[$this->prefix . 'userid']);
unset($_SESSION[$this->prefix . 'username']);
unset($_SESSION[$this->prefix . 'useragent']);
unset($_SESSION[$this->prefix . 'ip']);
unset($_SESSION[$this->prefix . 'logintime']);
unset($_SESSION[$this->prefix . 'realname']);
unset($_SESSION[$this->prefix . 'email']);
unset($_SESSION[$this->prefix . 'random']);
unset($_SESSION[$this->prefix . 'remember']);

if(!isset($sqlDel))
{
//ugh no references for the database found, so no database delete query.
throw new Exception('Database sessions couldn\'t be destroyed');
return false;
}
elseif($sqlDel)
{
return true;
}
else {
throw new exception('an error accured while deleting the session from the database');
return false;
}
}

function __destruct()
{
if($this->processTime == true)
{
//round on 6 characters, e.i 0.0034
echo '
'  . PHP_EOL;
echo '
'  . PHP_EOL;
echo 'Class processtime: ' . substr(microtime() - $this->startTime, 0, 6) . ' seconds
' . PHP_EOL;
}
}

}
?>

Reacties (6)

 
Whoops, miss is het handig om de database erbij te gooien :P
ik ga ff zoeken
 
            throw new Exception('No database connection aviable');

Available
 
@Robin moet zijn throw new Exception('No database connection available');  Ontopic: Ziet er netjes uit zover ik nu kan zien, zal er vanavond ff uitgebreid naar kijken :)
 
ja doe dan ff regelnr.s aub ^^ ik kan zo niet echt zien natuurlijk, en ja ik was heel moe (autorit) toen ik dit makte, dus vandaar het gefaal met engels
 
En wat als je een changing ip hebt (zoals sommige 3G-verbindingen lately)?
 
Citaat van: "jyy"
En wat als je een changing ip hebt (zoals sommige 3G-verbindingen lately)?
dan wordt je er telkens uit gemieterd... :')
[Reactie plaatsen]

Details

Avatar Thumb
Door: Thumb
Taal: PHP
7/11/2011 10:34
995x bekeken

Opties

Ik vind dit: Leuk  Niet leuk
Leuk
2
Niet leuk
0
Naar boven