Ver Mensaje Individual
  #9 (permalink)  
Antiguo 14/03/2012, 05:57
Avatar de humanista
humanista
 
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años, 7 meses
Puntos: 15
Respuesta: Sistema de logueo de usuarios

(sigue...)

Código PHP:
Ver original
  1. */
  2.  
  3. /**
  4.  * Flexible Access - The main class
  5.  *
  6.  * @param string $dbName
  7.  * @param string $dbHost
  8.  * @param string $dbUser
  9.  * @param string $dbPass
  10.  * @param string $dbTable
  11.  */
  12.  
  13. class flexibleAccess{
  14.   /*Settings*/
  15.   /**
  16.    * The database that we will use
  17.    * var string
  18.    */
  19.   var $dbName = 'database';
  20.   /**
  21.    * The database host
  22.    * var string
  23.    */
  24.   var $dbHost = 'localhost';
  25.   /**
  26.    * The database port
  27.    * var int
  28.    */
  29.   var $dbPort = 3306;
  30.   /**
  31.    * The database user
  32.    * var string
  33.    */
  34.   var $dbUser = 'user';
  35.   /**
  36.    * The database password
  37.    * var string
  38.    */
  39.   var $dbPass = 'password';
  40.   /**
  41.    * The database table that holds all the information
  42.    * var string
  43.    */
  44.   var $dbTable  = 'users';
  45.   /**
  46.    * The session variable ($_SESSION[$sessionVariable]) which will hold the data while the user is logged on
  47.    * var string
  48.    */
  49.   var $sessionVariable = 'userSessionValue';
  50.   /**
  51.    * Those are the fields that our table uses in order to fetch the needed data. The structure is 'fieldType' => 'fieldName'
  52.    * var array
  53.    */
  54.   var $tbFields = array(
  55.     'userID'=> 'userID',
  56.     'login' => 'username',
  57.     'pass'  => 'password',
  58.     'email' => 'email',
  59.     'active'=> 'active'
  60.   );
  61.     /**
  62.    * When user wants the system to remember him/her, how much time to keep the cookie? (seconds)
  63.    * var int
  64.    */
  65.   var $remTime = 2592000;//One month
  66.   /**
  67.    * The name of the cookie which we will use if user wants to be remembered by the system
  68.    * var string
  69.    */
  70.   var $remCookieName = 'ckSavePass';
  71.   /**
  72.    * The cookie domain
  73.    * var string
  74.    */
  75.   var $remCookieDomain = '';
  76.   /**
  77.    * The method used to encrypt the password. It can be sha1, md5 or nothing (no encryption)
  78.    * var string
  79.    */
  80.   var $passMethod = 'sha1';
  81.   /**
  82.    * Display errors? Set this to true if you are going to seek for help, or have troubles with the script
  83.    * var bool
  84.    */
  85.   var $displayErrors = true;
  86.   /*Do not edit after this line*/
  87.   var $userID;
  88.   var $dbConn;
  89.   var $userData=array();
  90.   /**
  91.    * Class Constructure
  92.    *
  93.    * @param string $dbConn
  94.    * @param array $settings
  95.    * @return void
  96.    */
  97.   function flexibleAccess($dbConn = '', $settings = '')
  98.   {
  99.         if ( is_array($settings) ){
  100.             foreach ( $settings as $k => $v ){
  101.                     if ( !isset( $this->{$k} ) ) die('Property '.$k.' does not exists. Check your settings.');
  102.                     $this->{$k} = $v;
  103.             }
  104.         }
  105.         $this->remCookieDomain = $this->remCookieDomain == '' ? $_SERVER['HTTP_HOST'] : $this->remCookieDomain;
  106.         $this->dbConn = ($dbConn=='')? mysql_connect($this->dbHost.':'.$this->dbPort, $this->dbUser, $this->dbPass):$dbConn;
  107.         if ( !$this->dbConn ) die(mysql_error($this->dbConn));
  108.         mysql_select_db($this->dbName, $this->dbConn)or die(mysql_error($this->dbConn));
  109.         if( !isset( $_SESSION ) ) session_start();
  110.         if ( !empty($_SESSION[$this->sessionVariable]) )
  111.         {
  112.             $this->loadUser( $_SESSION[$this->sessionVariable] );
  113.         }
  114.         //Maybe there is a cookie?
  115.         if ( isset($_COOKIE[$this->remCookieName]) && !$this->is_loaded()){
  116.           //echo 'I know you<br />';
  117.           $u = unserialize(base64_decode($_COOKIE[$this->remCookieName]));
  118.           $this->login($u['uname'], $u['password']);
  119.         }
  120.   }
  121.  
  122.   /**
  123.     * Login function
  124.     * @param string $uname
  125.     * @param string $password
  126.     * @param bool $loadUser
  127.     * @return bool
  128.   */
  129.   function login($uname, $password, $remember = false, $loadUser = true)
  130.   {
  131.         $uname    = $this->escape($uname);
  132.         $password = $originalPassword = $this->escape($password);
  133.         switch(strtolower($this->passMethod)){
  134.           case 'sha1':
  135.             $password = "SHA1('$password')"; break;
  136.           case 'md5' :
  137.             $password = "MD5('$password')";break;
  138.           case 'nothing':
  139.             $password = "'$password'";
  140.         }
  141.         $res = $this->query("SELECT * FROM `{$this->dbTable}`
  142.         WHERE `{$this->tbFields['login']}` = '$uname' AND `{$this->tbFields['pass']}` = $password LIMIT 1",__LINE__);
  143.         if ( @mysql_num_rows($res) == 0)
  144.             return false;
  145.         if ( $loadUser )
  146.         {
  147.             $this->userData = mysql_fetch_array($res);
  148.             $this->userID = $this->userData[$this->tbFields['userID']];
  149.             $_SESSION[$this->sessionVariable] = $this->userID;
  150.             if ( $remember ){
  151.               $cookie = base64_encode(serialize(array('uname'=>$uname,'password'=>$originalPassword)));
  152.               $a = setcookie($this->remCookieName,
  153.               $cookie,time()+$this->remTime, '/', $this->remCookieDomain);
  154.             }
  155.         }
  156.         return true;
  157.   }
  158.  
  159.   /**
  160.     * Logout function
  161.     * param string $redirectTo
  162.     * @return bool
  163.   */
  164.   function logout($redirectTo = '')
  165.   {
  166.     setcookie($this->remCookieName, '', time()-3600);
  167.     $_SESSION[$this->sessionVariable] = '';
  168.     $this->userData = '';
  169.     if ( $redirectTo != '' && !headers_sent()){
  170.        header('Location: '.$redirectTo );
  171.        exit;//To ensure security
  172.     }
  173.   }
  174.   /**
  175.     * Function to determine if a property is true or false
  176.     * param string $prop
  177.     * @return bool
  178.   */
  179.   function is($prop){
  180.     return $this->get_property($prop)==1?true:false;
  181.   }
  182.  
  183.     /**
  184.     * Get a property of a user. You should give here the name of the field that you seek from the user table
  185.     * @param string $property
  186.     * @return string
  187.   */
  188.   function get_property($property)
  189.   {
  190.     if (empty($this->userID)) $this->error('No user is loaded', __LINE__);
  191.     if (!isset($this->userData[$property])) $this->error('Unknown property <b>'.$property.'</b>', __LINE__);
  192.     return $this->userData[$property];
  193.   }
  194.   /**
  195.     * Is the user an active user?
  196.     * @return bool
  197.   */
  198.   function is_active()
  199.   {
  200.     return $this->userData[$this->tbFields['active']];
  201.   }
  202.  
  203.   /**
  204.    * Is the user loaded?
  205.    * @ return bool
  206.    */
  207.   function is_loaded()
  208.   {
  209.     return empty($this->userID) ? false : true;
  210.   }
  211.   /**
  212.     * Activates the user account
  213.     * @return bool
  214.   */
  215.   function activate()
  216.   {
  217.     if (empty($this->userID)) $this->error('No user is loaded', __LINE__);
  218.     if ( $this->is_active()) $this->error('Allready active account', __LINE__);
  219.     $res = $this->query("UPDATE `{$this->dbTable}` SET {$this->tbFields['active']} = 1
  220.     WHERE `{$this->tbFields['userID']}` = '".$this->escape($this->userID)."' LIMIT 1");
  221.     if (@mysql_affected_rows() == 1)
  222.     {
  223.         $this->userData[$this->tbFields['active']] = true;
  224.         return true;
  225.     }
  226.     return false;
  227.   }
  228.   /*
  229.    * Creates a user account. The array should have the form 'database field' => 'value'
  230.    * @param array $data
  231.    * return int
  232.    */  
  233.   function insertUser($data){
  234.     if (!is_array($data)) $this->error('Data is not an array', __LINE__);
  235.     switch(strtolower($this->passMethod)){
  236.       case 'sha1':
  237.         $password = "SHA1('".$data[$this->tbFields['pass']]."')"; break;
  238.       case 'md5' :
  239.         $password = "MD5('".$data[$this->tbFields['pass']]."')";break;
  240.       case 'nothing':
  241.         $password = $data[$this->tbFields['pass']];
  242.     }
  243.     foreach ($data as $k => $v ) $data[$k] = "'".$this->escape($v)."'";
  244.     $data[$this->tbFields['pass']] = $password;
  245.     $this->query("INSERT INTO `{$this->dbTable}` (`".implode('`, `', array_keys($data))."`) VALUES (".implode(", ", $data).")");
  246.     return (int)mysql_insert_id($this->dbConn);
  247.   }
  248.   /*
  249.    * Creates a random password. You can use it to create a password or a hash for user activation
  250.    * param int $length
  251.    * param string $chrs
  252.    * return string
  253.    */
  254.   function randomPass($length=10, $chrs = '1234567890qwertyuiopasdfghjklzxcvbnm'){
  255.     for($i = 0; $i < $length; $i++) {
  256.         $pwd .= $chrs{mt_rand(0, strlen($chrs)-1)};
  257.     }
  258.     return $pwd;
  259.   }
  260.   ////////////////////////////////////////////
  261.   // PRIVATE FUNCTIONS
  262.   ////////////////////////////////////////////
  263.  
  264.   /**
  265.     * SQL query function
  266.     * @access private
  267.     * @param string $sql
  268.     * @return string
  269.   */
  270.   function query($sql, $line = 'Uknown')
  271.   {
  272.     //if (defined('DEVELOPMENT_MODE') ) echo '<b>Query to execute: </b>'.$sql.'<br /><b>Line: </b>'.$line.'<br />';
  273.     $res = mysql_db_query($this->dbName, $sql, $this->dbConn);
  274.     if ( !res )
  275.         $this->error(mysql_error($this->dbConn), $line);
  276.     return $res;
  277.   }
  278.  
  279.   /**
  280.     * A function that is used to load one user's data
  281.     * @access private
  282.     * @param string $userID
  283.     * @return bool
  284.   */
  285.   function loadUser($userID)
  286.   {
  287.     $res = $this->query("SELECT * FROM `{$this->dbTable}` WHERE `{$this->tbFields['userID']}` = '".$this->escape($userID)."' LIMIT 1");
  288.     if ( mysql_num_rows($res) == 0 )
  289.         return false;
  290.     $this->userData = mysql_fetch_array($res);
  291.     $this->userID = $userID;
  292.     $_SESSION[$this->sessionVariable] = $this->userID;
  293.     return true;
  294.   }
  295.  
  296.   /**
  297.     * Produces the result of addslashes() with more safety
  298.     * @access private
  299.     * @param string $str
  300.     * @return string
  301.   */  
  302.   function escape($str) {
  303.     $str = get_magic_quotes_gpc()?stripslashes($str):$str;
  304.     $str = mysql_real_escape_string($str, $this->dbConn);
  305.     return $str;
  306.   }
  307.  
  308.   /**
  309.     * Error holder for the class
  310.     * @access private
  311.     * @param string $error
  312.     * @param int $line
  313.     * @param bool $die
  314.     * @return bool
  315.   */  
  316.   function error($error, $line = '', $die = false) {
  317.     if ( $this->displayErrors )
  318.         echo '<b>Error: </b>'.$error.'<br /><b>Line: </b>'.($line==''?'Unknown':$line).'<br />';
  319.     if ($die) exit;
  320.     return false;
  321.   }
  322. }
  323. ?>


Mi pregunta es cómo hago desde fuera de la clase para recuperar el valor de userID una vez conectado.

Se supone que $_SESSION[$sessionVariable] es una variable global que te da ese valor, es decir si desde fuera de la clase hago:

Código PHP:
echo $_SESSION[$sessionVariable]; 
me debería salir, no? El caso es que no lo hace