Error passing object by session in php

3

I'm doing a login, and the type of user is a different object, that object in the code that it queries if it works well, use a var_dump to the session variable where I used it and it works well, epro when I sent it no longer works.

Login.php

<?php
session_start();
require_once '../Modelo/PDOConex.php';

if((!$nameUser = trim($_POST['user'])) || (!$password = md5(trim($_POST['pass']) ) ) ){
header('location:../');
}

try{
$stmt = $db_con->prepare("SELECT 
    idUsuarios,
    Cuenta,
    Contra
FROM 
    Usuarios 
WHERE 
    Cuenta=:usuario");

$stmt->execute(array(":usuario"=>$nameUser));
$fila = $stmt->fetch(PDO::FETCH_ASSOC);

if($fila['Contra']==$password){ //Credenciales correctas

    require_once 'Log/getTipo.php';

    switch (getTipo($fila['idUsuarios'], $db_con)){

        case 'Administrativo':
            require_once 'Log/LoginAdmin.php';
            $_SESION['Usuario'] = serialize(logAdmin($fila['idUsuarios'], $db_con));
            $_SESION['Tipo']= 'Administrativo';
            break;
        case 'Docente':
            require_once 'Log/LoginDocente.php';
            $_SESION['Usuario'] = logDocente($fila['idUsuarios']);
            $_SESION['Tipo']= 'Docente';
            break;
        case 'Estudiante':
            require_once 'Log/LoginEstud.php';
            $_SESION['Usuario'] = logEst($fila['idUsuarios']);
            $_SESION['Tipo']= 'Estudiante';
            break;
        case 'Acudiente':
            require_once 'Log/LoginAcud.php';
            $_SESION['Usuario'] = logAcud($fila['idUsuarios']);
            $_SESION['Tipo']= 'Acudiente';
            break;
        default:
            echo "0";
            break;
    }
}else{
    echo '0'; // Credenciales incorrectas
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>  

index.php

<?php
require_once 'Controlador/Usuarios/Acudientes.php';
require_once 'Controlador/Usuarios/Administrativos.php';
require_once 'Controlador/Usuarios/Docentes.php';
require_once 'Controlador/Usuarios/Estudiantes.php';
session_start();

// Error You do not receive the object, here var_dump prints false ...

$_SESSION['Usuario'] = unserialize($_SESSION['Usuario'])
if(isset($_SESSION['Usuario'])){
    header('location:Pages/login.php');
}else{

switch($_SESSION['Tipo']){
    case 'Administrativo':
        if(count($_SESSION['Usuario']->getId_Colegio())>1){
            header('location:preAdmin.php');
        }else{
            header('location:indexAdmin.php');
        }
        break;
    case 'Docente':
        if(count($_SESSION['Usuario']->getId_Colegio())>1){
            header('location:preDocente.php');
        }else{
            header('location:indexDocente.php');
        }
        break;
    case 'Estudiante':
        header('location:indexEstudiante.php');
        break;
    case 'Acudiente':
        header('location:indexAcudiante.php');
        break;
    default:
        header('location:Controlador/logout.php');
        break;
    }
}

What am I failing?

    
asked by Johnny Pachecp 19.12.2016 в 05:11
source

1 answer

2

After executing the line that puts $_SESSION['Usuario'] = unserialize($_SESSION['Usuario']); the treated value will be saved as the content of the session variable $_SESSION['Usuario'] overwriting the original value, so the next time you go through that same line unserialize will return false because it will not be able to work a second time with some data already treated, also generating a notification type E_NOTICE (that you can be filtering depending on the configuration of your PHP).

You should use a temporary variable other than the session variable (so as not to modify and corrupt its content) to work with the data returned by unserialize :

$datos = unserialize($_SESSION['Usuario']);
switch($_SESSION['Tipo']){
    case 'Administrativo':
        if(count($datos->getId_Colegio())>1){
            header('location:preAdmin.php');
        }else{
            header('location:indexAdmin.php');
        }
        break;
    case 'Docente':
        if(count($datos->getId_Colegio())>1){
            header('location:preDocente.php');
        }else{
            header('location:indexDocente.php');
        }
        break;
    case 'Estudiante':
        header('location:indexEstudiante.php');
        break;
    case 'Acudiente':
        header('location:indexAcudiante.php');
        break;
    default:
        header('location:Controlador/logout.php');
        break;
    }
}

Also, you do not always use serialize to save the data in that session variable, so you should make your code homogeneous before to follow or use a different session variable that always contains the same type of content.

Functional minimum example:

/* Iniciamos el entorno de sesiones */
session_start();

/* Definimos una clase mínima con la que trabajar */
class Usuario
{
    /* El valor inicial del número al instanciar la clase será 0 */
    private $numero = 0;

    public function getNumero()
    {
        return $this->numero;
    }

    public function setNumero($numero)
    {
        $this->numero = $numero;
    }
}

/* Si no estaba definido el índice en la variable súperglobal
  de sesión instanciamos un nuevo usuario */ 
if (!isset($_SESSION['Usuario'])) {
    $_SESSION['Usuario'] = new Usuario();
}
/* Si en algún momento el contenido no es una instancia de Usuario lo decimos */
if (! $_SESSION['Usuario'] instanceof Usuario) {
    die('$_SESSION[\'Usuario\'] no es una instancia de Usuario.');
}
/* Mostramos el valor actual */
echo $_SESSION['Usuario']->getNumero() ."\n";
/* Incrementamos en uno el valor */
$_SESSION['Usuario']->setNumero($_SESSION['Usuario']->getNumero() + 1);

As you can see, every time we load the page the property $numero of the class Usuario is increased by one. That's because the state of the class is saved in the session variable.

    
answered by 19.12.2016 / 09:03
source