Ver Mensaje Individual
  #1 (permalink)  
Antiguo 23/02/2010, 18:01
Avatar de humanista
humanista
 
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 19 años
Puntos: 15
Recuperar una variable en una clase AJAX...

Hola, tengo q script de AJAX para logear un usuario. Realmente no entiendo gran cosa de AJAX, hice copy/paste y me funiona pero tengo un problema.

El script consulta una tabla con mail (usuario) y password (contraseña).

Resulta que necesito sacar el $id del usuario que se encuentra en la misma tabla q el usuario y contraseña.

El tema es que no se cómo hacerlo. Lo suyo sería aprender desde el principio las clases y lo he intentado pero es complicado, necesito tiempo y tan sólo me hace falta recuperar el id haciendo en la clase algo así como $id=$row[id]; pero obviamente lo he probado y no me funciona.

Este es el código (bastante largo por cierto):

Código PHP:
index.php

<?
  
include('logconfig.php');
  if (!
$login->logged())
  {
    
header("location: logindex.php");
    die();
  }

?>

____________________
forum.php

<? 
header
("Content-Type: text/html; charset=utf-8");  
?>
<?
  
include('logconfig.php');
  if (!
$login->logged())
  {
    
header("location: logindex.php");
    die();
  }
  else
  {
  
// recogemos el valor id
  
}?>

si es correcto el usuario y contraseña, aquí iría la web en sí...

_______________

logconfig.php

<?
  
include('loglogin.php');
  
  
$login = new login(array(
    
'database' => 'basedatos',
    
'table'    => 'tabla',
    
'mail' => 'root',
    
'password' => 'root'
  
));
?>
___________________

loglogin.php

<?
/*
 * @script      Sistema de logueo de usuarios
 * @version     0.3.b
 * @date        17 Agosto 2009
 * @copyright   Copyright (c) 2008-2009 - [url]www.codeflyer.org[/url] - All Rights Reserved.
 * @author      Eduardo Daniel Sada.
 * @license     MIT ( [url]http://es.wikipedia.org/wiki/Licencia_MIT[/url] )
*/

/* 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 
$id;
    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 id='{$this->id}' 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 id = '{$this->id}';"$this->link);
        return 
mysql_affected_rows($this->link)==true false;
    }

    public function 
lastlogin()
    {
        if (
$result mysql_query("SELECT lastactive FROM {$this->table} WHERE id = '{$this->id}' 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)
        {
          return 
$this->setSession($row$remember);
        }
        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->id         $values['id'];
    
$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 id='{$this->id}'"$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;
    }

    
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 id='{$this->id}'"$this->link);

    
$this->mail '';
    
$this->password '';
    
$this->privilege 0;
    
$this->id 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());
      }
    }

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

    
session_start();
    }

}

?>

Última edición por humanista; 25/02/2010 a las 01:40