5, December 2008

My improved version of the PHP User Class - webmaster forum

 
Webdigity webmaster forums
This forum shares its ad revenue with its members!
[ Home | Help | Search | Forum's Shop | Archive | Login | Register | Webmaster Directory ]
Webdigity Webmaster Forums  >  Web Development  >  PhP  >  Php User Class
Topic: My improved version of the PHP User Class
« previous next »
Pages: [1] Print

Author Topic: My improved version of the PHP User Class  (Read 745 times)
Chicken-run Manager
*
Posts: 9
58 credits
Members referred : 0


« on: Jun 13, 2008, 06:39:29 PM »

Hi there

The idea and methods of the php user class are very well, however I was a bit unhappy about the implementation.

That's why I got completely through the script and changed everything I disliked.

Here's my changelog:
Code:
- Now using php5
- Lot of cosmetics, coding is now more strict
- Added a lot of missing @ in the descriptions, which led to errors in the documentation
- Corrected wrong return types (in the description)
- Now using the object mysqli
- Fixed error "if(!res)" in the query() function
- Removed mysql_db_query() from query() (which used was deprecated)
- Improved sql-queries
- Added capitals to randomPass()
- Improved error capture (but didn't add try-catch)
- Renamed some functions (e.g. is_loaded() => isLoaded())
- Added alias for renamed functions
- Fixed spelling mistakes (and added some new ones ;))
- Made loadUser() explicit public (even it was anyway...)
- Added updateProperty()


Here it is:

Code:
<?php
/**
 * PHP Class for user access (login, register, logout, etc)
 * 
 * ==============================================================================
 * 
 * Rewritten by Michel Jung
 * 
 * @copyright Copyright (c) 2007 Nick Papanotas (http://www.webdigity.com)
 * @author Nick Papanotas <nikolas@webdigity.com>
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
 * 
 * ==============================================================================

 */

/**
 * Flexible Access - The main class
 * 
 * @param string $dbName
 * @param string $dbHost 
 * @param string $dbUser
 * @param string $dbPass
 * @param string $dbTable
 */

class flexibleAccess{
  
/*Settings*/
  /**
   * The database that we will use
   * var string
   */
  
private $dbName 'database';
  
/**
   * The database host
   * var string
   */
  
private $dbHost 'localhost';
  
/**
   * The database port
   * var int
   */
  
private $dbPort 3306;
  
/**
   * The database user
   * var string
   */
  
private $dbUser 'user';
  
/**
   * The database password
   * var string
   */
  
private $dbPass 'password';
  
/**
   * The database table that holds all the information
   * var string
   */
  
private $dbTable 'users';
  
/**
   * The session variable ($_SESSION[$sessionVariable]) which will hold the data while the user is logged on
   * var string
   */
  
private $sessionVariable 'userSessionValue';
  
/**
   * Those are the fields that our table uses in order to fetch the needed data. The structure is 'fieldType' => 'fieldName'
   * var array
   */
  
private $tbFields = array(
    
'userID'=> 'id'
    
'login' => 'username',
    
'pass'  => 'password',
    
'email' => 'email',
    
'active'=> 'active'
  
);
  
/**
   * When user wants the system to remember him/her, how much time to keep the cookie? (seconds)
   * var int
   */
  
private $remTime 2592000;//One month
  /**
   * The name of the cookie which we will use if user wants to be remembered by the system
   * var string
   */
  
private $remCookieName 'ckSavePass';
  
/**
   * The cookie domain
   * var string
   */
  
private $remCookieDomain '';
  
/**
   * The method used to encrypt the password. It can be sha1, md5 or nothing (no encryption)
   * var string
   */
  
private $passMethod 'sha1';
  
/**
   * Display errors? Set this to true if you are going to seek for help, or have troubles with the script
   * var bool
   */
  
public $displayErrors true;
  
/*Do not edit after this line*/
  
private $userID;
  
private $dbConn;
  
private $userData=array();
  
private $mysqli;
  
/**
   * Class Constructor
   * 
   * @access public
   * @param array $settings
   * @param object $mysqli
   * @return void
   */
  
public function __construct($settings '', &$mysqli NULL)
  {
    if (
is_array($settings))
    {
      foreach (
$settings as $k => $v)
      {
          if(!isset(
$this->{$k}))
            
$this->error('Property '.$k.' does not exists. Check your settings.'__LINE__true);

          
$this->{$k} = $v;
      }
    }

    
$this->remCookieDomain = ($this->remCookieDomain == '') ? $_SERVER['HTTP_HOST'] : $this->remCookieDomain;

    if(!isset(
$mysqli))
    {
      
$this->mysqli = @new mysqli($this->dbHost$this->dbUser$this->dbPass$this->dbName$this->dbPort);
      if(
mysqli_connect_errno())
        
$this->error(mysqli_connect_errno(), __LINE__true);
    }
    else
      
$this->mysqli $mysqli;

    if(!isset(
$_SESSION))
      
session_start();

    if(!empty(
$_SESSION[$this->sessionVariable]))
      
$this->loadUser($_SESSION[$this->sessionVariable]);

    
//Maybe there is a cookie?
    
if(isset($_COOKIE[$this->remCookieName]) && !$this->is_loaded())
    {
      
//echo 'I know you<br />';
      
$u unserialize(base64_decode($_COOKIE[$this->remCookieName]));
      
$this->login($u['uname'], $u['password']);
    }
  }

  
/**
    * Login function
    * @access public
    * @param string $uname
    * @param string $password
    * @param bool $loadUser
    * @return bool
  */
  
public function login($uname$password$remember false$loadUser true)
  {
    
$uname    $this->escape($uname);
    
$password $originalPassword $this->escape($password);

    switch(
strtolower($this->passMethod)){
      case 
'sha1':
        
$password sha1($password);
        break;
      case 
'md5' :
        
$password md5($password);
        break;
      case 
'':
      case 
'nothing':
        break;
      default:
        
$this->error('Unknown password method'__LINE__true);
    }

    
$result $this->query("SELECT * FROM `".$this->dbTable."`
                            WHERE `"
.$this->tbFields['login']."` = '".$uname."'
                              AND `"
.$this->tbFields['pass']."` = '".$password."'
                            LIMIT 1"
__LINE__);

    if(
$result)
    {
      if(
$result->num_rows == 0)
        return 
false;
      else
      {
        if(
$loadUser && $this->userData $result->fetch_assoc())
        {
          
$this->userID $this->userData[$this->tbFields['userID']];
          
$_SESSION[$this->sessionVariable] = $this->userID;
    
          if(
$remember)
          {
            
$cookie base64_encode(serialize(array('uname'=>$uname,'password'=>$originalPassword)));
            if(!@
setcookie($this->remCookieName$cookie,time()+$this->remTime'/'$this->remCookieDomain))
            {
              
$this->error("Couldn't set cookie"__LINE__);
              return 
false;
            }  
          }
          return 
true;
        }
      }
    }
    else
    {
      
$this->error($this->mysqli->error__LINE__true);
      return 
false;
    }
  }

  
/**
    * Logout function
    * @access public
    * @param string $redirectTo
    * @return void
  */
  
public function logout($redirectTo '')
  {
    @
setcookie($this->remCookieName''1'/'$this->remCookieDomain);
    @
setcookie("PHPSESSID"''1'/'$this->remCookieDomain);
    unset(
$_SESSION[$this->sessionVariable]);
    unset(
$this->userData);

    if(
$redirectTo != '' && !headers_sent())
    {
      
header('Location: '.$redirectTo);
      exit; 
//To ensure security
    
}
  }

  
/**
    * Function to determine if a property is true or false
    * @access public
    * @param string $prop
    * @return bool
  */
  
public function is($prop){
    return (
$this->get_property($prop)==1) ? true false;
  }

  
/**
    * Get a property of a user. You should give here the name of the field that you seek from the user table
    * @access public
    * @param string $property
    * @return mixed
  */
  
public function getProperty($property)
  {
    if(empty(
$this->userID))
      
$this->error('No user is loaded'__LINE__);
    elseif(!isset(
$this->userData[$property]))
      
$this->error('Unknown property <b>'.$property.'</b>'__LINE__);
    else
      return 
$this->userData[$property];
  }

  
/**
    * Alias for getProperty() (for compatibility)
    * @access public
    * @param string $property
    * @return mixed
  */
  
public function get_property($property)
  {
    return 
$this->getProperty($property);
  }

  
/**
    * Is the user an active user?
    * @access public
    * @return bool
  */
  
public function isActive()
  {
    return 
$this->userData[$this->tbFields['active']];
  }

  
/**
    * Alias for isActive() (for compatibility)
    * @access public
    * @return bool
  */
  
function is_active()
  {
    return 
$this->isActive();
  }

  
/**
   * Is the user loaded?
   * @access public
   * @ return bool
   */
  
function isLoaded()
  {
    return empty(
$this->userID) ? false true;
  }

  
/**
   * Alias for isLoaded() (for compatibility)
   * @access public
   * @ return bool
   */
  
function is_loaded()
  {
    return 
$this->isLoaded();
  }

  
/**
    * Activates the user account. Returns:
    * -1 if the user isn't loaded
    * 0 if the user couldn't be activated
    * 1 if the user was actvated
    * 2 if the user is already active
    * 
    * @access public
    * @return int
  */
  
public function activate()
  {
    if(empty(
$this->userID))
      return -
1;
    elseif(
$this->is_active())
      return 
2;
    else
    {
      
$result $this->query("UPDATE `".$this->dbTable."`
                                SET `"
.$this->tbFields['active']."` = 1 
                              WHERE `"
.$this->tbFields['userID']."` = '".$this->escape($this->userID)."'
                              LIMIT 1"
__LINE__);
      if(
$result)
      {
        if(
$this->mysqli->affected_rows == 1)
        {
          
$this->userData[$this->tbFields['active']] = true;
          return 
1;
        }
        else
          return 
0;
      }
      else
        return 
0;
    }
  }

  
/*
   * Creates an user account. The array have to be in the form of 'database field' => 'value'
   * Returns the user id on success or FALSE on failure
   * @access Public
   * @param array $data
   * @return mixed
   */  
  
public function insertUser($data)
  {
    if(!
is_array($data))
    {
      
$this->error('Data is not an array'__LINE__);
      return 
false;
    }
    else
    {
      switch(
strtolower($this->passMethod))
      {
        case 
'sha1':
          
$data[$this->tbFields['pass']] = sha1($data[$this->tbFields['pass']]);
          break;
        case 
'md5' :
          
$data[$this->tbFields['pass']] = md5($data[$this->tbFields['pass']]);
          break;
        case 
'':
        case 
'nothing':
          
$password $data[$this->tbFields['pass']];
          break;
        default:
          return 
false;
      }

      foreach (
$data as $k => $v )
        
$data[$k] = "'".$this->escape($v)."'";

      
$result $this->query("INSERT INTO `".$this->dbTable."` (
                                `"
.implode('`, `'array_keys($data))."`)
                              VALUES
                                ("
.implode(", "$data).")"__LINE__);
      if(!
$result)
        return 
false;
      else
        return (int) 
$this->mysqli->insert_id;
    }
  }

  
/*
   * Creates a random password. You can use it to create a password or a hash for user activation
   * @param int $length
   * @param string $chrs
   * @return string
   */
  
public function randomPass($length=10$chrs '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFHGJKLZXCVBNM')
  {
    for(
$i 0$i $length$i++)
        
$pwd .= $chrs{mt_rand(0strlen($chrs)-1)};

    return 
$pwd;
  }
  
  
/*
   * Updates a property. Data must be in the form 'property' => 'value'
   * @param array
   * @return bool
   */
  
public function updateProperty($properties)
  {
    if(
is_array($properties) && count($properties) > 1)
    {
      
$i=1;
      
$query "UPDATE `".$this->dbTable."` SET ";

      foreach(
$properties AS $k => $v)
      {
        if(!isset(
$this->userData[$k]))
        {
          if(
$k == $this->tbFields['pass'])
          {
            switch(
strtolower($this->passMethod))
            {
              case 
'sha1':
                
$v sha1($v);
                break;
              case 
'md5' :
                
$v md5($v);
                break;
              default:
            }
          }
          
$query .= "`".$this->escape($k)."` = '".$this->escape($v)."'".(($i++ < count($properties)) ? ', ' ' ');
        }
        else
          
$this->error('Unknown Property <b>'.$k.'</b>'__LINE__);
      }

      
$query .= "WHERE `".$this->tbFields['userID']."` = '".$this->userID."'";

      if(
$this->mysqli->query($query))
        return 
true;
      else
      {
        
$this->error($this->mysqli->error__LINE__);
        return 
false;
      }
    }
    else
      return 
false;
  }

  
/**
    * A function that is used to load one user's data
    * @access private
    * @param string $userID
    * @return bool
  */
  
public function loadUser($userID)
  {
    
$result $this->query("SELECT * FROM `".$this->dbTable."`
                            WHERE
                              `"
.$this->tbFields['userID']."` = '".$this->escape($userID)."'
                            LIMIT 1"
__LINE__);

    if(
$result->num_rows == 0)
      return 
false;
    else
    {
      
$this->userData $result->fetch_array();
      
$this->userID $userID;
      
$_SESSION[$this->sessionVariable] = $this->userID;

      return 
true;
    }
  }

  
////////////////////////////////////////////
  // PRIVATE FUNCTIONS
  ////////////////////////////////////////////
  
  /**
    * SQL query function
    * @access private
    * @param string $sql
    * @return string
  */
  
private function query($sql$line 'Unknown')
  {
    
//if (defined('DEVELOPMENT_MODE') ) echo '<b>Query to execute: </b>'.$sql.'<br /><b>Line: </b>'.$line.'<br />';
    
$result $this->mysqli->query($sql);
    if(!
$result)
      
$this->error($this->mysqli->error$line);
    return 
$result;
  }

  
/**
    * Produces the result of addslashes() with more safety
    * @access private
    * @param string $str
    * @return string
  */  
  
private function escape($str)
  {
    
$str get_magic_quotes_gpc() ? stripslashes($str) : $str;
    return 
$this->mysqli->real_escape_string($str);
  }
  
  
/**
    * Error holder for the class
    * @access private
    * @param string $error
    * @param int $line
    * @param bool $die
    * @return void
  */  
  
private function error($error$line 0$die false)
  {
    if(
$this->displayErrors)
      echo 
'<b>Error: </b>'.$error.'<br /><b>Line: </b>'.($line==0?'Unknown':$line).'<br />';
    if(
$die)
      exit;
  }
}
?>

Have fun
« Last Edit: Jul 04, 2008, 12:09:16 AM by Downlord »
I am a metal monkey!
Administrator
Community Supporter ?
Jedai Sword Master
*****
Gender: Male
Posts: 8272
42619 credits
Members referred : 3



« Reply #1 on: Jun 14, 2008, 03:55:01 PM »

Thanks for your contribution Smiley

I like that you are using php 5 - in fact I wanted to switch to php5 too - but I don't like that you are using mysqli.

I think I will take your code and make a version that will use both mysql and mysqli extensions for maximum compatibility.

Thanks again, being open source is cool Smiley

Trial and Error my two best teachers Cool
Join us @ facebook Visit through proxy or twitter Visit through proxy

Last blog : Free Unlimited Bandwith and disk space to good to be true?
Chicken-run Manager
*
Posts: 9
58 credits
Members referred : 0


« Reply #2 on: Jun 15, 2008, 03:23:02 PM »

Oh man... I pasted an untested version xD and I used tabs...
sorry, but I was in hurry Smiley I'll paste the corrected version later Wink

Edit:
Ok I corrected the errors, but I didn't test the class completely!
See code above

Edit2:
Why don't you like mysqli? Because it has to be installed?
« Last Edit: Jun 15, 2008, 04:16:29 PM by Downlord »
Chicken-run Manager
*
Posts: 9
58 credits
Members referred : 0


« Reply #3 on: Jun 15, 2008, 10:24:46 PM »

Last versions had a lot of crap-code... so it didn't work.

now this one should work better Wink
Chicken-run Manager
*
Posts: 9
58 credits
Members referred : 0


« Reply #4 on: Jun 16, 2008, 02:35:46 PM »

Google dot what?
*
Posts: 2
12 credits
Members referred : 0


« Reply #5 on: Jul 03, 2008, 12:59:22 AM »

Neat improvements !

However, when you write in the construct :
  if(isset($mysqli))
      if(!$this->mysqli = new mysqli($this->dbHost etc.
Don't you mean "if(!isset" (=if not isset) ? Since the parameter $mysqli is defaulted to NULL when you initialize the class, isset is false in your if loop, thus $this->mysqli is always NULL. Which is bad, as they say in Ghostbusters.

Does it make sense ? Am I missing something ? Wink
Chicken-run Manager
*
Posts: 9
58 credits
Members referred : 0


« Reply #6 on: Jul 04, 2008, 12:10:32 AM »

No, you aren't missing something Smiley Ty for that. Even I forgot to set {} there and the logout didn't work...

These things are now solved Smiley
Google dot what?
*
Posts: 2
12 credits
Members referred : 0


« Reply #7 on: Jul 04, 2008, 10:13:59 PM »

Cool ! By, the way, thank you both for this nice work. It saved me a lot of work, and I learned a couple of tricks, that's a winner combo.

Not to mention that your cryptic discussion about mysqli convinced me to take a closer look at it. I love Open Source, too  Wink
Trackback URI for this entry : http://www.webdigity.com/trackback.php?topic=7782
Tags : php user class Bookmark this thread : Digg Del.icio.us Dzone more....

Topic sponsors:
Get a permanent link here for $1.99!


Pages: [1] Print 
Webdigity Webmaster Forums  >  Web Development  >  PhP  >  Php User Class
Topic: My improved version of the PHP User Class
« previous next »
Jump to:
User Area
Welcome, Guest. Please login or register.
Did you miss your activation email?
Dec 05, 2008, 04:40:30 PM





Login with username, password and session length

Donate to our community, and get a permanent link back to your site!

Donate to our community, and get a permanent link back to your site!


Forum Statistics
Total Posts: 38.000
Total Topics: 7.685
Total Members: 4.470
Tutorials : 56
Resources : 143
Designs : 220
Latest Member: srinivasarao

35 Guests, 3 Users online :

9 users online today:



Readers

Web Design Gallery · Whois Lookup · Pagerank · Tag Browsing · Lo-fi version · Syndication · Webmaster forum history · Advertise
Developed by HumanWorks © 2005 - 2008 Webdigity webmaster community · sublime directory
Webdigity Webmaster Forums | Powered by SMF 1.0.