From cb1fc66c66482cc8db5d3776a474fce87b4b105f Mon Sep 17 00:00:00 2001 From: Luis Cabrera Benito Date: Mon, 7 Jan 2019 13:54:11 -0600 Subject: [PATCH] Introduciendo sesiones --- BD.php | 12 ++++++++ Sesion.php | 75 +++++++++++++++++++++++++++++++++++++++++++++++ SesionService.php | 67 ++++++++++++++++++++++++++++++++++++++++++ Utiles.php | 10 ++----- env.ejemplo.php | 8 +++++ index.php | 25 ++++++++++------ navegacion.php | 49 +++++++++++++++++-------------- 7 files changed, 208 insertions(+), 38 deletions(-) create mode 100644 SesionService.php diff --git a/BD.php b/BD.php index 3a80faf..519886f 100644 --- a/BD.php +++ b/BD.php @@ -14,4 +14,16 @@ public static function obtener() $bd->query("SET NAMES 'utf8'"); return $bd; } + public static function obtenerParaSesion() + { + $bd = new PDO( + "mysql:host=" . Comun::env("HOST_MYSQL_SESION") . ";dbname=" . Comun::env("NOMBRE_BD_MYSQL_SESION"), + Comun::env("USUARIO_MYSQL_SESION"), + Comun::env("PASS_MYSQL_SESION") + ); + $bd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + $bd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $bd->query("SET NAMES 'utf8'"); + return $bd; + } } diff --git a/Sesion.php b/Sesion.php index e69de29..d9386e6 100644 --- a/Sesion.php +++ b/Sesion.php @@ -0,0 +1,75 @@ +base_de_datos = BD::obtenerParaSesion(); + return true; + } + + public function close() + { + #Eliminamos referencia a la base de datos + $this->base_de_datos = null; + return true; + } + + public function write($id_de_sesion, $datos_de_sesion) + { + $ultimo_acceso = time(); + $sentencia = $this->base_de_datos->prepare("REPLACE INTO sesiones (id, datos, ultimo_acceso) VALUES (?, ?, ?);"); + return $sentencia->execute([$id_de_sesion, $datos_de_sesion, $ultimo_acceso]); + } + + public function read($id_de_sesion) + { + $sentencia = $this->base_de_datos->prepare("SELECT datos FROM sesiones WHERE id = ?;"); + $sentencia->execute([$id_de_sesion]); + # Recuperar como objeto (con PDO::FETCH_OBJ), para acceder a $fila->datos + $fila = $sentencia->fetch(PDO::FETCH_OBJ); + + # Si no existen datos con ese id, fetch devuelve FALSE + if ($fila === false) { + return ""; # Cadena vacía + } else { + return $fila->datos; + } + } + + public function destroy($id_de_sesion) + { + $sentencia = $this->base_de_datos->prepare("DELETE FROM sesiones WHERE id = ?;"); + return $sentencia->execute([$id_de_sesion]); + } + + public function gc($tiempo_de_vida) + { + #Calculamos el tiempo actual menos el tiempo de vida. + $caducidad = time() - $tiempo_de_vida; + + $sentencia = $this->base_de_datos->prepare("DELETE FROM sesiones WHERE ultimo_acceso < ?;"); + return $sentencia->execute([$caducidad]); + } + +} \ No newline at end of file diff --git a/SesionService.php b/SesionService.php new file mode 100644 index 0000000..85f2ff5 --- /dev/null +++ b/SesionService.php @@ -0,0 +1,67 @@ + +