Foros del Web » Programando para Internet » PHP »

Sistema de logueo de usuarios

Estas en el tema de Sistema de logueo de usuarios en el foro de PHP en Foros del Web. Hola, tengo un sistema de logueo de usuarios que me funciona bien en local pero lo subo al servidor y no va bien. Concretamente lo ...
  #1 (permalink)  
Antiguo 11/03/2012, 13:02
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Sistema de logueo de usuarios

Hola, tengo un sistema de logueo de usuarios que me funciona bien en local pero lo subo al servidor y no va bien. Concretamente lo que me falla es el "keep me logged".
En local sí pero no en el servidor.
El tema es que tengo un formulario como éste:

Código HTML:
Ver original
  1. <form name="loginform" method="post" action="index.php">
  2. <input type="text" name="mail" maxlength="100" />
  3. <input type="password" class="ver12neg" name="password" />
  4. <input type="checkbox" id="remember" name="remember" value="on" checked />
  5. <input type="submit" name="submit" value="entrar" />
  6. </form>

que conecta con esto:

Código PHP:
    if ($_POST['submit'])
    {
        if (
$_POST['remember'] == "on")
        {
            
$remember true;
        }
        else
        {
            
$remember false;
        }

        if(
$login->login($_POST['mail'], $_POST['password'], $remember))
        {     
                        
// ..............................
        


continúa... (por falta de espacio)
  #2 (permalink)  
Antiguo 11/03/2012, 13:03
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Y la función login y todo el resto del sistema de logueo está en otro archivo que os pego:


Código PHP:
<?
/*
 * @script      Sistema de logueo de usuarios
 * @version     0.3.b
 * @date        17 Agosto 2009
 * @copyright   Copyright (c) 2008-2009 - www.codeflyer.org - All Rights Reserved.
 * @author      Eduardo Daniel Sada.
 * @license     MIT ( http://es.wikipedia.org/wiki/Licencia_MIT )
 http://www.coders.me/php/sistema-de-logueo-de-usuarios-en-php-mysql
*/

/* PHP5 required */
if (version_compare(PHP_VERSION'5.0.0') < 0)
{
    die(
'The CodeFlyer Framework requires PHP 5.x.x or greater.');
}


class 
login
{
    private 
$mail;
    private 
$password;
    private 
$privilege;

    private 
$link;
    private 
$idprofile;
    private 
$table;
    
    public 
$error;

  
/**
   * Get userdata
   */

  
public function get($var)
  {
    
$var trim(lcase($var));

    if (
$var=='privilege')
    {
      
$ret $this->privilege;
    }
    else if (
$var=='mail')
    {
      
$ret $this->mail;
    }
    else if (
$var=='password')
    {
      
$ret $this->password;
    }
    else
    {
      
$ret false;
    }
    return 
$ret;
  }


  public function 
isadmin()
    {
    return 
$this->privilege == 1;
    }

    public function 
getdata($data)
    {
    
$data $this->clean(trim($data));
    
$query "SELECT $data FROM {$this->table} WHERE idprofile='{$this->idprofile}' LIMIT 1;";
    if (
$result mysql_query($query$this->link))
    {
      if (
$row mysql_fetch_assoc($result))
      {
        return 
$row[$data];
      }
    }
    }

  
/**
   * Set userdata
   */
    
public function modlastlogin()
    {
        
mysql_query("UPDATE {$this->table} SET lastactive = NOW() WHERE idprofile = '{$this->idprofile}';"$this->link);
        return 
mysql_affected_rows($this->link)==true false;
    }

    public function 
lastlogin()
    {
        if (
$result mysql_query("SELECT lastactive FROM {$this->table} WHERE idprofile = '{$this->idprofile}' LIMIT 1"$this->link))
        {
            if (
$row mysql_fetch_assoc($result))
            {
                return 
$row['lastactive'];
            }
        }
    }

    
/**
     * Login core
     */
    
public function inherit($session)
    {
    
session_name(urldecode($session));
    }

    public function 
getSID()
    {
    return 
"PHPSESSID=".session_id();
    }

  public function 
login($mail$password$remember false)
  {
    
$mail $this->clean($mail);
    
$password md5($password);
    
$query    "SELECT * FROM {$this->table} WHERE mail = '$mail' LIMIT 1;";

    if (
$result mysql_query($query$this->link))
    {
      if (
$row mysql_fetch_assoc($result))
      {
        if (
$row['password']==$password AND $row['onoff']<>2//si el usuario y la contraseña y además ya he activado el perfil (onoff<>2), me logueo
        
{
          return 
$this->setSession($row$remember);
          return 
$this->idprofile=$values['idprofile'];
          
        }
        else
        {
          
$this->logout();
          
$this->error 'pi'// Password Incorrect
          
return false;
        }
      }
      
$this->logout();
      
$this->error 'ui'// mail Incorrect
      
return false;
    }
    else
    {
      
$this->logout();
      return 
false;
    }
  }
  
  
// Construir la session y la cookie, y guardarlas en la base de datos.
  
private function setSession(&$values$remember false$init true)
  {
    
$this->idprofile   $values['idprofile'];
    
$this->mail       $values['mail'];
    
$this->password   $values['password'];
    
$this->privilege  $values['privilege'];

    
$_SESSION['cf_login_mail'] = htmlspecialchars($this->mail);
    
    
$cookie md5($values['mail'].date("Y-m-d"));
    if (
$remember)
    {
      
$this->update_cookie($cookietrue);
    }

    if (
$init)
    {
      
$session session_id();
      
mysql_query("UPDATE {$this->table} SET session='{$session}', cookie='{$cookie}' WHERE idprofile='{$this->idprofile}'"$this->link);
      
$this->modlastlogin();
    }
    return 
true;
  }

  private function 
update_cookie($cookie)
  {
    
$this->create_cookie('cf_login_cookie'serialize(array($this->mail$this->password$cookie)), time() + 31104000);
  }
  
  public function 
create_cookie($name$value=''$maxage=0$domain=''$path=''$secure=false$HTTPOnly=false)
  {
    
$ob ini_get('output_buffering');
    
    if (
$_SERVER['HTTPS'])
    {
      
$secure true;
    }

    
// Abort the method if headers have already been sent, except when output buffering has been enabled
    
if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
    {
      return 
false;
    }

    if (!(bool)
$maxage)
    {
      
$maxage time()+3600;
    }

    if ( !empty(
$domain) )
    {
      
// Fix the domain to accept domains with and without 'www.'.
      
if ( strtolowersubstr($domain04) ) == 'www.' )
      {
        
$domain substr($domain4);
      }

      
// Add the dot prefix to ensure compatibility with subdomains
      
if ( substr($domain01) != '.' )
      {
        
$domain '.'.$domain;
      }


      
// Remove port information.
      
$port strpos($domain':');

      if ( 
$port !== false )
      {
        
$domain substr($domain0$port);
      }
    }
    else
    {
      
// Localhost compatibility
      
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
    }
    
    
$path="/";
    
    
header('Set-Cookie: ' .rawurlencode($name).'='.rawurlencode($value)
                          .(empty(
$domain) ? '' '; Domain='.$domain )
                          .(empty(
$maxage) ? '' '; Max-Age='.$maxage)
                          .(empty(
$path)   ? '' '; Path='.$path     )
                          .(!
$secure       '' '; Secure'          )
                          .(!
$HTTPOnly     '' '; HttpOnly'        )
          , 
false);
    return 
true;
  }

  
// Devuelve true si el usuario está logueado. Caso contrario devuelve false.
  // @return bool
    
public function logged()
    {
    
// Verificar si el usuario contiene una cookie y cargar sus datos.
    
$cookie = array();
    if (
$_COOKIE['cf_login_cookie'])
    {
      list(
$cookie['mail'], $cookie['password'], $cookie['serial']) = @unserialize(stripslashes($_COOKIE['cf_login_cookie']));
    }

    
// Verificar si los datos de la cookie son válidos.
    
if ($cookie['serial'] && $cookie['mail'] && $cookie['password'])
    {
      
$query    "SELECT * FROM {$this->table} WHERE (mail = '{$cookie['mail']}') AND (password = '{$cookie['password']}') AND (cookie = '{$cookie['serial']}') LIMIT 1;";
    }
    else
    {
      
// Verificar si los datos de session son válidos.
      
$mail $_SESSION['cf_login_mail'];
      
$session  session_id();
      
$query    "SELECT * FROM {$this->table} WHERE (mail = '$mail') AND (session = '$session') LIMIT 1;";
    }


    if (
$result mysql_query($query$this->link))
    {
      if (
$row mysql_fetch_assoc($result))
      {
        return 
$this->setSession($rowfalsefalse); // Log in        
      
}
      else
      {
        return 
false;
      }
    }
    else
    {
      return 
false;
    }
    }

  
// Destruir sessión.
    
public function logout()
    {
        
$_SESSION['cf_login_mail'] = '';
        
$_SESSION['cf_login_cookie'] = 0;
        
$this->create_cookie('cf_login_cookie'''time() - 3600);
        
mysql_query("UPDATE {$this->table} SET session='".strtoupper(md5(time()))."', cookie='".strtoupper(md5(time()))."' WHERE idprofile='{$this->idprofile}'"$this->link);

        
$this->mail '';
        
$this->password '';
        
$this->privilege 0;
        
$this->idprofile 0;
    }

  
// Limpia la variable de carácteres impuros.
  
private function clean($value)
  {
    if (
get_magic_quotes_gpc())
    {
      
$value stripslashes($value);
    }
    
$value mysql_real_escape_stringhtmlspecialchars$value ) );
    return 
$value;
  }

  
// Crea la clase y conecta con la base de datos.
  // @param array : ['host']     = 'localhost';
  //                ['table']    = Tabla en donde se almacenan los usuarios
  //                ['mail'] = Nombre de usuario de la base de datos
  //                ['password'] = Password de la base de datos 
    
public function __construct($array)
    {
    
$this->table $array['table'] ? $array['table'] : 'login';
    
$this->link  mysql_connect$array['host'] ? $array['host'] : 'localhost'$array['mail'], $array['password'], true );
    if (!
$this->link)
    {
      die(
mysql_error());
    }
    else
    {
      if (!
mysql_select_db($array['database']))
      {
        die(
mysql_error());
      }
    }
    
mysql_query ("SET NAMES 'utf8'"); // se añadió para evitar problema con el uft8

    
if (isset($_GET['PHPSESSID']))
    {
      
session_id($_GET['PHPSESSID']);
    }

    
session_start();  // quitado pq no funciona en el servidor
    
}

    function 
getMail()
    {
        return 
$this->mail;
    }
    
    function 
getPassword()
    {
        return 
$this->password;        
    }
    
}

?>

Vale, con todo esto me crea 2 cookies PHPSESSID que es la cookie normal de sesión, esté logueado o no y luego la que me interesa más y que es donde creo que falla, se llama cf_login_cookie y me está trayendo de cabeza...

Última edición por humanista; 11/03/2012 a las 13:09
  #3 (permalink)  
Antiguo 11/03/2012, 13:10
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

(sigo porque no tenía espacio)

El tema es que en local me crea esa cookie con contenido pero en el servidor me la crea vacía. Creo que el error puede estar en su creación, por aquí:


Código PHP:
Ver original
  1. $this->create_cookie('cf_login_cookie', serialize(array($this->mail, $this->password, $cookie)), time() + 31104000);
o por aquí:

Código PHP:
Ver original
  1. header('Set-Cookie: ' .rawurlencode($name).'='.rawurlencode($value)
  2.                           .(empty($domain) ? '' : '; Domain='.$domain )
  3.                           .(empty($maxage) ? '' : '; Max-Age='.$maxage)
  4.                           .(empty($path)   ? '' : '; Path='.$path     )
  5.                           .(!$secure       ? '' : '; Secure'          )
  6.                           .(!$HTTPOnly     ? '' : '; HttpOnly'        )
  7.           , false);

Pero no consigo detectar dónde está el fallo. Entiendo que el problema no es fácil de resolver (al menos para mí)
  #4 (permalink)  
Antiguo 12/03/2012, 15:31
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Puede ser del servidor?


He revisado el phpinfo() en local y en el servidor y he visto una diferencia que creo que puede ser la causa del error.


- local:
Registered serializer handlers: php php_binary wddx

WDDX Support enabled
WDDX Session Serializer enabled


- servidor:
Registered serializer handlers: php php_binary



lo digo porque mirando también en el servidor el valor de las cookies, precisamente la que creo causante del error, está a blancos:

_COOKIE["cf_login_cookie"]: no value
  #5 (permalink)  
Antiguo 12/03/2012, 16:27
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Sistema de logueo de usuarios

Algo raro que veo en tu clase es el método login, que tiene dos returns, no se que tanto afecte eso pero no esta bien...

Ahora veo que quitaste un session_start() porque dices que no lo soporta el servidor ¿a que te refieres con eso?
  #6 (permalink)  
Antiguo 12/03/2012, 16:51
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Lo del session start es un comentario sin importancia, en su día lo quité pero lo he vuelto a poner tal y como se muestra en el código.

A qué 2 returns te refieres?

Me he dado también cuenta de que en Internet Explorer y en Opera (ahora hablo en local) no me va el remember (keep me logged) pero en Chrome, Mozilla y Safari sí (siempre en local).

Al subirlo al server no me va en ninguno.
  #7 (permalink)  
Antiguo 12/03/2012, 17:19
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Sistema de logueo de usuarios

A esto:
Código PHP:
Ver original
  1. public function login($mail, $password, $remember = false)
  2.   {
  3.     $mail = $this->clean($mail);
  4.     $password = md5($password);
  5.     $query    = "SELECT * FROM {$this->table} WHERE mail = '$mail' LIMIT 1;";
  6.  
  7.     if ($result = mysql_query($query, $this->link))
  8.     {
  9.       if ($row = mysql_fetch_assoc($result))
  10.       {
  11.         if ($row['password']==$password AND $row['onoff']<>2) //si el usuario y la contraseña y además ya he activado el perfil (onoff<>2), me logueo
  12.         {
  13.           return $this->setSession($row, $remember);
  14.           return $this->idprofile=$values['idprofile'];
  15.            
  16.         }

Saludos.
  #8 (permalink)  
Antiguo 14/03/2012, 05:55
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Buff, pues no sé, esta clase la veo un poco chunga, no sé si alguien sabe alguna clase para hacer login de usuarios con función remember me (keep me logged).

Por ahora he encontrado esta que estoy intentando ajustar a mi web:

Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * PHP Class to user access (login, register, logout, etc)
  4.  *
  5.  * <code><?php
  6.  * include('access.class.php');
  7.  * $user = new flexibleAccess();
  8.  * ? ></code>
  9.  *
  10.  * For support issues please refer to the webdigity forums :
  11.  *              http://www.webdigity.com/index.php/board,91.0.html
  12.  * or the official web site:
  13.  *              http://phpUserClass.com/
  14.  * ==============================================================================
  15.  *
  16.  * @version $Id: access.class.php,v 0.93 2008/05/02 10:54:32 $
  17.  * @copyright Copyright (c) 2007 Nick Papanotas (http://www.webdigity.com)
  18.  * @author Nick Papanotas <[email protected]>
  19.  * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
  20.  *
  21.  * ==============================================================================

(continúa que es larga)
  #9 (permalink)  
Antiguo 14/03/2012, 05:57
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
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
  #10 (permalink)  
Antiguo 14/03/2012, 10:35
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Sistema de logueo de usuarios

Pues en las propiedades de la app $userID es una variable pública por lo que usando la instancia de la clase podrías obtener el valor sin usar $_SESSION.

Saludos.
  #11 (permalink)  
Antiguo 14/03/2012, 11:52
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

y eso cómo puedo hacerlo? Gracias
  #12 (permalink)  
Antiguo 14/03/2012, 12:11
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Sistema de logueo de usuarios

Pues todo depende de como lo instancies, por ejemplo:

Código PHP:
Ver original
  1. $user = new flexibleAccess();
  2. $id = $user->userID;

Saludos.
  #13 (permalink)  
Antiguo 14/03/2012, 13:37
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Gracias, funciona!!!
  #14 (permalink)  
Antiguo 16/03/2012, 03:34
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Vaya...

Ahora tengo otro problema, cuando hago logout me desconecta correctamente pero me sale este error:

Warning: Cannot modify header information - headers already sent by (output started at /home/virtual/miweb.com/admin/index.php:5) in /home/virtual/miweb.com/admin/access.class.php on line 192

la línea 192 es ésta (dentro de la función logout):

Código PHP:
Ver original
  1. setcookie($this->remCookieName, '', time()-3600);

El tema es que al destruir la cookie creo que interviene esta línea con cabeceras:

Código PHP:
Ver original
  1. $this->remCookieDomain = $this->remCookieDomain == '' ? $_SERVER['HTTP_HOST'] : $this->remCookieDomain;

Que es posible que sea donde "casque". Podría ser de la session_start() pero la tengo puesta al principio de todas las páginas que intervienen en el proceso y no hay espacios antes de ella.

La funcionalidad "remember me" (variable $remember) es decir que me cree una cookie para mantenerme logueado, también usa cabeceras:

Código PHP:
Ver original
  1. $a = setcookie($this->remCookieName,
  2.               $cookie,time()+$this->remTime, '/', $this->remCookieDomain);

y tampoco funciona (de hecho no me crea la cookie, lo he comprobado), lo digo por si sirve de pista.
  #15 (permalink)  
Antiguo 16/03/2012, 09:29
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Sistema de logueo de usuarios

El mismo warning te lo dice:

Warning: Cannot modify header information - headers already sent by (output started at /home/virtual/miweb.com/admin/index.php:5) in /home/virtual/miweb.com/admin/access.class.php on line 192

La salida empieza en index.php en la línea 5, tienes que ir a esa línea y evitar la salida de texto que tengas ahí.

Saludos.
  #16 (permalink)  
Antiguo 17/03/2012, 04:19
Avatar de humanista  
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Respuesta: Sistema de logueo de usuarios

Tenías razón!. Gracias GavtorV me has ayudado mucho.

Etiquetas: formulario, logueo, sistema, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:08.