Ver Mensaje Individual
  #1 (permalink)  
Antiguo 31/12/2010, 07:41
Avatar de humanista
humanista
 
Fecha de Ingreso: abril-2005
Mensajes: 878
Antigüedad: 18 años, 11 meses
Puntos: 15
Keep me logged (mantenerme conectado)

Hola, tengo un script para logear a un usuario con su correspondiente contraseña.

También hay una opción para hacer LOGOUT.

El tema es que quiero implementar una opción para que aparezca un check y se mantenga logeado la próxima vez que reinicie el ordenador.

Alguien sabe cómo? la teoría supongo que es fácil, el tema es no borrar la cookie que controla el usuario y la contraseña pero... cómo hacerlo?

os pego el código:

Código PHP:
Ver original
  1. /*
  2.  * @script      Sistema de logueo de usuarios
  3.  * @version     0.3.b
  4.  * @date        17 Agosto 2009
  5.  * @copyright   Copyright (c) 2008-2009 - www.codeflyer.org - All Rights Reserved.
  6.  * @author      Eduardo Daniel Sada.
  7.  * @license     MIT ( http://es.wikipedia.org/wiki/Licencia_MIT )
  8. */
  9.  
  10. /* PHP5 required */
  11. if (version_compare(PHP_VERSION, '5.0.0') < 0)
  12. {
  13.     die('The CodeFlyer Framework requires PHP 5.x.x or greater.');
  14. }
  15.  
  16.  
  17. class login
  18. {
  19.     private $mail;
  20.     private $password;
  21.     private $privilege;
  22.  
  23.     private $link;
  24.     private $idprofile;
  25.     private $table;
  26.    
  27.     public $error;
  28.  
  29.   /**
  30.    * Get userdata
  31.    */
  32.  
  33.   public function get($var)
  34.   {
  35.     $var = trim(lcase($var));
  36.  
  37.     if ($var=='privilege')
  38.     {
  39.       $ret = $this->privilege;
  40.     }
  41.     else if ($var=='mail')
  42.     {
  43.       $ret = $this->mail;
  44.     }
  45.     else if ($var=='password')
  46.     {
  47.       $ret = $this->password;
  48.     }
  49.     else
  50.     {
  51.       $ret = false;
  52.     }
  53.     return $ret;
  54.   }
  55.  
  56.  
  57.   public function isadmin()
  58.     {
  59.     return $this->privilege == 1;
  60.     }
  61.  
  62.     public function getdata($data)
  63.     {
  64.     $data = $this->clean(trim($data));
  65.     $query = "SELECT $data FROM {$this->table} WHERE idprofile='{$this->idprofile}' LIMIT 1;";
  66.     if ($result = mysql_query($query, $this->link))
  67.     {
  68.       if ($row = mysql_fetch_assoc($result))
  69.       {
  70.         return $row[$data];
  71.       }
  72.     }
  73.     }
  74.  
  75.   /**
  76.    * Set userdata
  77.    */
  78.     public function modlastlogin()
  79.     {
  80.         mysql_query("UPDATE {$this->table} SET lastactive = NOW() WHERE idprofile = '{$this->idprofile}';", $this->link);
  81.         return mysql_affected_rows($this->link)==1 ? true : false;
  82.     }
  83.  
  84.     public function lastlogin()
  85.     {
  86.         if ($result = mysql_query("SELECT lastactive FROM {$this->table} WHERE idprofile = '{$this->idprofile}' LIMIT 1", $this->link))
  87.         {
  88.             if ($row = mysql_fetch_assoc($result))
  89.             {
  90.                 return $row['lastactive'];
  91.             }
  92.         }
  93.     }
  94.  
  95.     /**
  96.      * Login core
  97.      */
  98.     public function inherit($session)
  99.     {
  100.     session_name(urldecode($session));
  101.     }
  102.  
  103.     public function getSID()
  104.     {
  105.     return "PHPSESSID=".session_id();
  106.     }
  107.  
  108.   public function login($mail, $password, $remember = false)
  109.   {
  110.     $mail = $this->clean($mail);
  111.     $password = md5($password);
  112.     $query    = "SELECT * FROM {$this->table} WHERE mail = '$mail' LIMIT 1;";
  113.  
  114.     if ($result = mysql_query($query, $this->link))
  115.     {
  116.       if ($row = mysql_fetch_assoc($result))
  117.       {
  118.         if ($row['password']==$password)
  119.         {
  120.           return $this->setSession($row, $remember);
  121.           //return $this->id=$values['id'];
  122.          
  123.         }
  124.         else
  125.         {
  126.           $this->logout();
  127.           $this->error = 'pi'; // Password Incorrect
  128.           return false;
  129.         }
  130.       }
  131.       $this->logout();
  132.       $this->error = 'ui'; // mail Incorrect
  133.       return false;
  134.     }
  135.     else
  136.     {
  137.       $this->logout();
  138.       return false;
  139.     }
  140.   }
  141.  
  142.   // Construir la session y la cookie, y guardarlas en la base de datos.
  143.   private function setSession(&$values, $remember = false, $init = true)
  144.   {
  145.     $this->idprofile   = $values['idprofile'];
  146.     $this->mail       = $values['mail'];
  147.     $this->password   = $values['password'];
  148.     $this->privilege  = $values['privilege'];
  149.  
  150.     $_SESSION['cf_login_mail'] = htmlspecialchars($this->mail);
  151.    
  152.     $cookie = md5($values['mail'].date("Y-m-d"));
  153.     if ($remember)
  154.     {
  155.       $this->update_cookie($cookie, true);
  156.     }
  157.  
  158.     if ($init)
  159.     {
  160.       $session = session_id();
  161.       mysql_query("UPDATE {$this->table} SET session='{$session}', cookie='{$cookie}' WHERE idprofile='{$this->idprofile}'", $this->link);
  162.       $this->modlastlogin();
  163.     }
  164.     return true;
  165.   }
  166.  
  167.   private function update_cookie($cookie)
  168.   {
  169.     $this->create_cookie('cf_login_cookie', serialize(array($this->mail, $this->password, $cookie)), time() + 31104000);
  170.   }
  171.  
  172.   public function create_cookie($name, $value='', $maxage=0, $domain='', $path='', $secure=false, $HTTPOnly=false)
  173.   {
  174.     $ob = ini_get('output_buffering');
  175.    
  176.     if ($_SERVER['HTTPS'])
  177.     {
  178.       $secure = true;
  179.     }
  180.  
  181.     // Abort the method if headers have already been sent, except when output buffering has been enabled
  182.     if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )
  183.     {
  184.       return false;
  185.     }
  186.  
  187.     if (!(bool)$maxage)
  188.     {
  189.       $maxage = time()+3600;
  190.     }
  191.  
  192.     if ( !empty($domain) )
  193.     {
  194.       // Fix the domain to accept domains with and without 'www.'.
  195.       if ( strtolower( substr($domain, 0, 4) ) == 'www.' )
  196.       {
  197.         $domain = substr($domain, 4);
  198.       }
  199.  
  200.       // Add the dot prefix to ensure compatibility with subdomains
  201.       if ( substr($domain, 0, 1) != '.' )
  202.       {
  203.         $domain = '.'.$domain;
  204.       }
  205.  
  206.  
  207.       // Remove port information.
  208.       $port = strpos($domain, ':');
  209.  
  210.       if ( $port !== false )
  211.       {
  212.         $domain = substr($domain, 0, $port);
  213.       }
  214.     }
  215.     else
  216.     {
  217.       // Localhost compatibility
  218.       $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
  219.     }
  220.  
  221.     header('Set-Cookie: ' .rawurlencode($name).'='.rawurlencode($value)
  222.                           .(empty($domain) ? '' : '; Domain='.$domain )
  223.                           .(empty($maxage) ? '' : '; Max-Age='.$maxage)
  224.                           .(empty($path)   ? '' : '; Path='.$path     )
  225.                           .(!$secure       ? '' : '; Secure'          )
  226.                           .(!$HTTPOnly     ? '' : '; HttpOnly'        )
  227.           , false);
  228.     return true;
  229.   }
  230.  
  231.   // Devuelve true si el usuario está logueado. Caso contrario devuelve false.
  232.   // @return bool
  233.     public function logged()
  234.     {
  235.     // Verificar si el usuario contiene una cookie y cargar sus datos.
  236.     $cookie = array();
  237.     if ($_COOKIE['cf_login_cookie'])
  238.     {
  239.       list($cookie['mail'], $cookie['password'], $cookie['serial']) = @unserialize(stripslashes($_COOKIE['cf_login_cookie']));
  240.     }
  241.  
  242.     // Verificar si los datos de la cookie son válidos.
  243.     if ($cookie['serial'] && $cookie['mail'] && $cookie['password'])
  244.     {
  245.       $query    = "SELECT * FROM {$this->table} WHERE (mail = '{$cookie['mail']}') AND (password = '{$cookie['password']}') AND (cookie = '{$cookie['serial']}') LIMIT 1;";
  246.     }
  247.     else
  248.     {
  249.       // Verificar si los datos de session son válidos.
  250.       $mail = $_SESSION['cf_login_mail'];
  251.       $session  = session_id();
  252.       $query    = "SELECT * FROM {$this->table} WHERE (mail = '$mail') AND (session = '$session') LIMIT 1;";
  253.     }
  254.  
  255.  
  256.     if ($result = mysql_query($query, $this->link))
  257.     {
  258.       if ($row = mysql_fetch_assoc($result))
  259.       {
  260.         return $this->setSession($row, false, false); // Log in    
  261.       }
  262.       else
  263.       {
  264.         return false;
  265.       }
  266.     }
  267.     else
  268.     {
  269.       return false;
  270.     }
  271.     }
  272.  
  273.   // Destruir sessión.
  274.     public function logout()
  275.     {
  276.         $_SESSION['cf_login_mail'] = '';
  277.         $_SESSION['cf_login_cookie']   = 0;
  278.         $this->create_cookie('cf_login_cookie', '', time() - 3600);
  279.         mysql_query("UPDATE {$this->table} SET session='".strtoupper(md5(time()))."', cookie='".strtoupper(md5(time()))."' WHERE idprofile='{$this->idprofile}'", $this->link);
  280.  
  281.         $this->mail = '';
  282.         $this->password = '';
  283.         $this->privilege = 0;
  284.         $this->idprofile = 0;
  285.     }
  286.  
  287.   // Limpia la variable de carácteres impuros.
  288.   private function clean($value)
  289.   {
  290.     {
  291.       $value = stripslashes($value);
  292.     }
  293.     $value = mysql_real_escape_string( htmlspecialchars( $value ) );
  294.     return $value;
  295.   }
  296.  
  297.   // Crea la clase y conecta con la base de datos.
  298.   // @param array : ['host']     = 'localhost';
  299.   //                ['table']    = Tabla en donde se almacenan los usuarios
  300.   //                ['mail'] = Nombre de usuario de la base de datos
  301.   //                ['password'] = Password de la base de datos
  302.     public function __construct($array)
  303.     {
  304.     $this->table = $array['table'] ? $array['table'] : 'login';
  305.     $this->link  = mysql_connect( $array['host'] ? $array['host'] : 'localhost', $array['mail'], $array['password'], true );
  306.     if (!$this->link)
  307.     {
  308.       die(mysql_error());
  309.     }
  310.     else
  311.     {
  312.       if (!mysql_select_db($array['database']))
  313.       {
  314.         die(mysql_error());
  315.       }
  316.     }
  317.     mysql_query ("SET NAMES 'utf8'"); // se añadió para evitar problema con el uft8
  318.  
  319.     if (isset($_GET['PHPSESSID']))
  320.     {
  321.       session_id($_GET['PHPSESSID']);
  322.     }
  323.  
  324.     session_start();  // quitado pq no funciona en el servidor
  325.     }
  326.  
  327.     function getMail()
  328.     {
  329.         return $this->mail;
  330.     }
  331.    
  332.     function getPassword()
  333.     {
  334.         return $this->password;    
  335.     }
  336.  
  337.     // function getName()
  338.     // {
  339.         // return $this->firsname;
  340.         // return $this->lastname;
  341.     // }
  342.    
  343. }