Error using $ _SESSION [] with unserialize: "expects parameter 1 to be string"

0

I need help finding an error.

So it looks like a BOM signature is popping up before session_start() . I have already searched all files (for Notepad++ ) and all are utf-8 sem BOM .

The structure of my pages is like this:

<?php
  require_once("testaAdmin.php");
  require_once("../_global/_erros/erros.ini");
  require_once("../_controlls/_util/Constantes.php");
  $constantes = new Constantes();
?>
<!DOCTYPE html>
<html>
<head>
 <title><?php echo $constantes->getTituloSiteAdmin(); ?></title>
 <?php  require_once("../_global/_meta/meta.ini"); ?>
 <link rel="shortcut icon" type="image/x-icon" href="../_img/favicon.ico" />
 <link type="text/css" rel="stylesheet" href="_global/_css/admin.css" />
 <link type="text/css" rel="stylesheet" href="_global/_css/menu.css" />
</head>
<body>
   <div id="topo"><h1><?php echo $constantes->getCabecalhoAdmin(); ?></h1></div>
   <div id="menu">
      <div class="sessoes"><?php require_once($menu.".php"); ?></div>
   </div>
   <div id="cont">
     <?php   
        if($adminLogado->getTipo() != "s" && $_GET["admin"] != $adminLogado->getIdAdmins())       {
            echo "<h1 class='h1CentralizadoAvisos'>Você não tem autorização para alterar este Administrador</h1>";
        }
        else  {
        ?>
            <div class="sessoes"><?php require_once("administradoresEditarConteudo.php"); ?></div>
        <?php
        }
      ?>
   </div>   
   <div id="base">
      <div class="sessoes"><?php require_once($base.".php"); ?></div>
   </div>
   <div id="final">
      <div class="sessoes"><?php require_once("final.php"); ?></div>
   </div>
</body>
</html>

The page testaAdmin.php

<?php  
  session_start();

  header  ("Content-Type: text/html; charset=utf-8");

  require_once("../_controlls/_models/Admins.php");
  require_once("../_controlls/_util/TestaAdmin.php");

  $testaAdmin = new TestaAdmin();
  $testaAdmin->validaAdmin($_SESSION["admin"]);

  if(!$testaAdmin->getAdminValido())  {

      echo "<script>location.href='index.php?erroadmin=".urlencode('Voc&ecirc; n&atilde;o esta logado. Por favor faça Login')."'</script>";


  } else {

      $adminLogado = unserialize($_SESSION["admin"]);

      if ($adminLogado->getBloqueado() == "s") {

          session_destroy();
          echo "<script>location.href='index.php?erroadmin=".urlencode('Administrador Bloqueado. Por favor faça contato com o gerente Administrador!')."'</script>";


      }
      $testaAdmin->setTextoCabecalho($adminLogado);
      $testaAdmin->setMenu($adminLogado);
      $testaAdmin->setBase($adminLogado);

      $menu = $testaAdmin->getMenu();
      $base = $testaAdmin->getBase();

      echo $testaAdmin->getTextoCabecalho();
  }
?>

All my pages follow this scheme and differ only on content pages.

Only one page is this error

Warning: unserialize() expects parameter 1 to be string, object given in /home/dimoveis/public_html/novo/admin/testaAdmin.php on line 19

Fatal error: Call to a member function getBloqueado() on a non-object in /home/dimoveis/public_html/novo/admin/testaAdmin.php on line 21

Follows Class TestaAdmin

<?php
  class TestaAdmin {    

     private $adminValido;
     private $textoCabecalho;
     private $menu;
     private $base;

     public function __construct () {
     }

     public function validaAdmin ($sessao) {

        $this->adminValido = isset($sessao)  ? true : false;

     }

     public function setTextoCabecalho ($admin) {

        $this->textoCabecalho = "<h6 style='text-align:center; width:1000px;'>Seja bem vindo Administrador ". $admin->getNome()." => <a href='logout.php' style='color:#000'>Sair</a></h6><br /><br />";

     }

     public function setMenu ($admin) {

        $this->menu = ($admin->getTipo() == "s") ? "menu" : "menu2";

     }

     public function setBase ($admin) {

        $this->base = ($admin->getTipo() == "c") ? "base2" : "base";
     }

     public function getAdminValido() {
         return $this->adminValido;
     }

     public function getTextoCabecalho() {
         return $this->textoCabecalho;
     }

      public function getMenu () {
          return $this->menu;
      }

      public function getBase () {
          return $this->base;
      }


  }
?>

Where will this error be?

Class Admins

<?php 

 class Admins {

     private $idAdmins;
     private $tipo;
     private $nome;
     private $login;
     private $senha;
     private $bloqueado;

     public function __construct ($_tipo, $_nome, $_login, $_senha, $_bloqueado) {       
         $this->tipo = $_tipo;
         $this->nome = $_nome;
         $this->login = $_login;
         $this->senha = $_senha;
         $this->bloqueado = $_bloqueado;
     }

     public function setIdAdmins ($_idAdmins) {
         $this->idAdmins = $_idAdmins;
     }

     public function getIdAdmins () {
         return $this->idAdmins;
     }

     public function getTipo () {
         return $this->tipo;
     }

     public function getNome () {
         return $this->nome;
     }

     public function getLogin () {
         return $this->login;
     }

     public function getSenha () {
         return $this->senha;
     }

     public function getBloqueado () {
         return $this->bloqueado;
     }

 }
?>

logon.php

<?php
require_once "../_controlls/_conexao/Conexao.php";
require_once "../_controlls/_models/Admins.php";
require_once "../_controlls/_daos/AdminsDao.php";


$connection = new Conexao();
$conexao = $connection->abreConexao();
$AdminsDao = new AdminsDao($conexao);

if (!isset($_GET["acao"])) {
    $erroadmin = (isset($_GET["erroadmin"])) ? $_GET["erroadmin"] : "";
?>
  <h1>Logar no Sistema</h1><br />
  <h3 class="avisos"><?php echo $erroadmin; ?></h3>

  <form action="" method="post">
    <input type="hidden" name="acao" value="logar" /> <br />
    <label class="labelPequeno">Login</label><input type="text" class="typeTextMedio" maxlength="<?php echo $constantes->getLenLogin(); ?>" name="login" required />  <br /> <br />
    <label class="labelPequeno">Senha</label><input type="password" class="typeTextMedio" maxlength="<?php echo $constantes->getLenSenha(); ?>" name="senha" required /> <br /> <br />
    </label><input type="submit" value="Enviar" /><br /> <br />
  </form>

<?php   
}

if (isset($_POST["acao"]) && $_POST["acao"] == "logar") {

      $login = $_POST["login"];
      $senha = $_POST["senha"];

    if( $login == "" || $senha == "" ) {

        echo "<label class='avisos'>erro: Algum campo esta vazio. Verifique</label>";

    } else {

        if ( strlen($login) > $constantes->getLenLogin() || strlen($senha) > $constantes->getLenSenha() ) {

            echo "<label class='avisos'>Login ou Senha com quantidade de caracters errado!</label>";
        } else {

            $admin = $AdminsDao->pesquisaAdmin($login, $senha);

            if($admin == null)  {

                echo "<label class='avisos'>Usuário ou senha inválidos</label>";

            } else {    

                if($admin->getBloqueado() == "s"){

                    echo "<label class='avisos'>".$admin->getNome().": O Administrador geral bloqueou você!</label>";
                } else {                        

                        $_SESSION["admin"] = serialize($admin);

                        echo "<script>location.href='principal.php'</script>";

                }
            }

            $connection->fechaConexao();

        }
    }   

}
?>
    
asked by anonymous 08.04.2016 / 21:51

3 answers

1

The error message is very clear. At line 19 of testaAdmin.php:

$adminLogado = unserialize($_SESSION["admin"]);

The unserialize() parameter is expected to be string , but is entering a object . That is, $_SESSION["admin"] is an object already ready, does not need or can not be deserialized.

Otherwise, remove the ?> from your files when they are at the end. It avoids problem of spaces after the end of the file, which can be so annoying to fix as the invisible spaces before <?php .

    
08.04.2016 / 22:15
0

I assume that in order to solve it, it would suffice to remove the function unserialize() :

$adminLogado = $_SESSION["admin"];

But anyway, I do not know what it contains within $_SESSION["admin"] . So it is unfeasible to point out a solution with the information you put in the question.

The unserialize () function expects a string as a parameter.

To tell you a solution for your case, we need to understand why you want to use $adminLogado = unserialize($_SESSION["admin"]); .

I assume that $ _SESSION ["admin"] should already be serialized with the serialize () function. But because of the error message, it's not what's really happening.

The question is, at what point $_SESSION["admin"] is serialized? I did not read the entire code you posted. If you can show where this occurs, it may make it easier to find the problem.

To better understand the problem, take a test to see what kind of variable:

var_dump($_SESSION["admin"]); exit;
$adminLogado = unserialize($_SESSION["admin"]);

Please enter your test result in your question.

It is probably an array or an object / stdclass.

    
09.04.2016 / 09:53
0

I have. The solution was:

In the form login file, which is where I create the session.

In the textaAdmin file, which is where I text the session.

It turns out that in order to get ALL the session object, session_start () must be declared after the require_once of the object class.

NOTE: This error does not occur on localhost. Only on the server.

<?php  

  header  ("Content-Type: text/html; charset=utf-8");

  require_once("../_controlls/_models/Admins.php");
  require_once("../_controlls/_util/TestaAdmin.php");        

  session_start();

  $testaAdmin = new TestaAdmin();
  $testaAdmin->validaAdmin($_SESSION["admin"]);
  ...

Thank you for all opinions regarding the question.

But if you had to use the singleton pattern to instantiate the TestaAdmin class once and it saves for each page a copy of the object for not using session would be better. But I searched a lot on the internet and tried a lot too and nothing.

    
09.04.2016 / 16:18