Ver Mensaje Individual
  #22 (permalink)  
Antiguo 11/11/2011, 08:07
Avatar de Uncontroled_Duck
Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 12 años, 11 meses
Puntos: 261
Respuesta: mostrar usuarios conectados a la web

La clase no tiene que tener salida de nada a la vista. El constructor solo se encarga de armar las variables y conexiones.

Te dejo una muy básica, ya la tienes que adaptar para que funcione con tu proyecto.

Tienes que poner los archivos index.php y class.sessions.php en el mismo directorio.
Abres index.php en el navegador despues de crear la tabla y editar los datos de conexión en la clase sessions.
Si cambias alguna variable de la clase, asegurate que has cambiado todas de la misma forma, si no podrás encontrarte errores y no funcionará correctamente.

Pruébala e intenta entender su funcionamiento antes de cambiar algo.

La tabla: MySql
Código MySQL:
Ver original
  1. CREATE TABLE `sessions` (
  2.   `session_id` varchar(32) COLLATE utf8_bin DEFAULT NULL,
  3.   `last_impression` int(11) NOT NULL,
  4.   `created` int(11) NOT NULL,
  5.   PRIMARY KEY (`id`),
  6.   UNIQUE KEY `id` (`id`),
  7.   UNIQUE KEY `session_id` (`session_id`)

La clase sessions:
Código PHP:
Ver original
  1. <?php
  2. /** Error Report */
  3. //comentar las dos líneas siguientes para evitar el reporte de errores
  4. ini_set("display_errors", 1);
  5.  
  6. /**
  7.  * Class para controlar sessiones
  8.  * class.sessions.php
  9.  */
  10. class sessions
  11. {
  12.     private $php_session_id;
  13.     private $native_session_id;
  14.     private $session_timeout  = 900; //tiempo en segundos de inactividad - 900 = 15 minutos
  15.     private $session_lifespan = 1800; //tiempo total en segundos de la session - 1800 = 30 minutos
  16.     private $sDB; // select DB
  17.     private $cDB; // conect DB
  18.     private $dDB = array('localhost', 'root', 'root', 'forosdelweb'); // datos DB, por defecto root, root
  19.  
  20.     /**
  21.      * constructor
  22.      */
  23.     public function __construct()
  24.     {
  25.         //conexión a la db
  26.         $this->cDB = mysql_connect(!$this->dDB[0] ? 'localhost' : $this->dDB[0], $this->dDB[1], $this->dDB[2])
  27.                 or die("Mensaje que quieras mostrar (" . mysql_error() . ")");
  28.         $this->sDB = mysql_select_db($this->dDB[3], $this->cDB)
  29.                 or die("mensaje que quieras mostrar (" . mysql_error() . ")");
  30.        
  31.         //estableces el controlador
  32.                 array(&$this, '_open_method'),
  33.                 array(&$this, '_close_method'),
  34.                 array(&$this, '_read_method'),
  35.                 array(&$this, '_write_method'),
  36.                 array(&$this, '_destroy_method'),
  37.                 array(&$this, '_gc_method')
  38.         );
  39.        
  40.         if( isset($_COOKIE["PHPSESSID"]) )
  41.         {
  42.             //seguridad y comprobación de tiempo
  43.             $this->php_session_id = $_COOKIE["PHPSESSID"];
  44.             $time = time();
  45.             $select = "SELECT id FROM sessions WHERE session_id = \"$this->php_session_id\" ";
  46.             $select.= "AND (($time - created) < '$this->session_lifespan') ";
  47.             $select.= "AND (($time - last_impression) <= '$this->session_timeout' ";
  48.             $select.= "OR last_impression IS NULL)";
  49.             $result = mysql_query($select);
  50.             if( mysql_num_rows($result) == 0 )
  51.             {
  52.                 //eliminar de la base de datos; al mismo tiempo, eliminar la basura
  53.                 $select = "DELETE FROM sessions ";
  54.                 $select.= "WHERE (session_id = '$this->php_session_id') ";
  55.                 $select.= "OR ($time - created > '$this->session_lifespan')";
  56.                 $result = mysql_query($select);
  57.                 //deshacerse de esta... obligamos a PHP a darnos una válida
  58.                 unset($_COOKIE["PHPSESSID"]);
  59.             }
  60.         }
  61.        
  62.         session_set_cookie_params($this->session_lifespan);
  63.         //el sesion start ya lo das aquí, no necesitas ponerlo en el resto de archivos.
  64.         session_start();
  65.     }
  66.    
  67.     /**
  68.      * Realiza impresiones de tiempo por cada petición.
  69.      */
  70.     public function impress()
  71.     {
  72.         if( $this->native_session_id )
  73.         {
  74.             $time = time();
  75.             $result = mysql_query("UPDATE sessions SET last_impression = $time WHERE id = '$this->native_session_id'");
  76.         }
  77.     }
  78.    
  79.     /**
  80.      * retorna el sesid del usuario
  81.      */
  82.     public function getSessionId()
  83.     {
  84.         return $this->php_session_id;
  85.     }
  86.    
  87.     public function getConect()
  88.     {
  89.         return $this->cDB;
  90.     }
  91.    
  92.     /**
  93.      * open method
  94.      * @param type $save_path
  95.      * @param type $session_name
  96.      * @return type
  97.      */
  98.     private function _open_method($save_path, $session_name)
  99.     {
  100.         //no hacer nada
  101.         return true;
  102.     }
  103.    
  104.     /**
  105.      * close method
  106.      * @return type
  107.      */
  108.     public function _close_method()
  109.     {
  110.         mysql_close($this->cDB);
  111.         return true;
  112.     }
  113.    
  114.     /**
  115.      * read method
  116.      * @param type $id
  117.      * @return type
  118.      */
  119.     public function _read_method($id)
  120.     {
  121.         $this->php_session_id = $id;
  122.        
  123.         //comprobar si existe en la base de datos o no
  124.         $result = mysql_query("SELECT id FROM sessions WHERE session_id = '$id'");
  125.         if( mysql_num_rows($result) > 0 )
  126.         {
  127.             $row = mysql_fetch_array($result);
  128.             $this->native_session_id = $row["id"];
  129.         }
  130.         else
  131.         {
  132.             //tenemos que crear una entrada en la base de datos
  133.             $time = time();
  134.             $result = mysql_query("INSERT INTO sessions(session_id, created)
  135.                                    VALUES ('$id', '$time')");
  136.             //obtenemos el ID verdadedro
  137.             $result = mysql_query("SELECT id FROM sessions WHERE session_id = '$id'");
  138.             $row = mysql_fetch_array($result);
  139.             $this->native_session_id = $row["id"];
  140.         }
  141.         //devolver un string vacío
  142.         return '';
  143.     }
  144.    
  145.     /**
  146.      * write method
  147.      * @param type $id
  148.      * @param type $sess_data
  149.      * @return type
  150.      */
  151.     public function _write_method($id, $sess_data)
  152.     {
  153.         return true;
  154.     }
  155.  
  156.     /**
  157.      * destroy method
  158.      * @param type $id
  159.      * @return type
  160.      */
  161.     private function _destroy_method($id)
  162.     {
  163.         $result = mysql_query("DELETE FROM sessions WHERE session_id = '$id'");
  164.         return $result;
  165.     }
  166.  
  167.     /**
  168.      * gc method
  169.      * @param type $maxlifetime
  170.      * @return type
  171.      */
  172.     private function _gc_method($maxlifetime)
  173.     {
  174.         return true;
  175.     }
  176.    
  177. }
  178. ?>

Un archivo para probarla:
Código PHP:
Ver original
  1. <?php
  2. require_once('class.sessions.php');
  3. $session = new sessions();
  4. $session->impress();
  5. /**
  6.  * index.php
  7.  * Esto va en todas las páginas
  8.  * No debes poner NADA antes de este código
  9.  *
  10.  * La conexión está ya incluida en la clase
  11.  */
  12. ?>
  13. <!--
  14. To change this template, choose Tools | Templates
  15. and open the template in the editor.
  16. -->
  17. <!DOCTYPE html>
  18. <html>
  19.     <head>
  20.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  21.         <title></title>
  22.     </head>
  23.     <body>        
  24.         Estado de la conexión: <?php
  25.         //conexión a la db
  26.         echo ( mysql_connect())? 'Está conectada.': 'No está conectada.';
  27.         ?>
  28.         <br />
  29.         <br />
  30.        
  31.         El id de sesion actual es: <?php echo $session->getSessionId() ?>
  32.         <br />
  33.         <br />
  34.        
  35.         <?php
  36.         //puedes trabajar añadiendo directamente la conexión ala query con:
  37.         //$session->getConect();
  38.         $select = 'SELECT id, session_id, last_impression, created ';
  39.         $select.= 'FROM sessions ';
  40.         $select.= "WHERE session_id = '" . $session->getSessionId() . "'";
  41.         $result = mysql_query($select, $session->getConect());
  42.  
  43.         if(  mysql_num_rows($result) > 0 )
  44.         {
  45.             $row = mysql_fetch_array($result);
  46.         }
  47.         ?>
  48.         Datos de la DB:<br />
  49.         Id: <?php echo $row['id'] ?> <br />
  50.         Session: <?php echo $row['session_id'] ?> <br />
  51.         Ultima impresión: <?php echo $row['last_impression'] ?> <br />
  52.         Creada:: <?php echo $row['created'] ?>
  53.     </body>
  54. </html>

Saludos,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight