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

Asked

Viewed 993 times

0

I need help finding an error.

From the looks of it is a signature GOOD who’s showing up before the session_start(). I’ve searched all the files (by Notepad++) and everyone is utf-8 sem BOM.

The structure of my pages are that way:

<?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 in content pages.

Only one page 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 the 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 is that mistake?

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();

        }
    }   

}
?>
  • The problem is not quite with session_start, recommend to make more intuitive titles to the problem =) - understand as a constructive criticism

  • Oh William, thank you for hello. I’ll be more attentive. But it’s just that at the time, it was this title that came to mind that related more to the problem that I understood was going through

  • A doubt Carlos, why are you trying to use unserialize with a session variable? Wouldn’t it be better to keep as variable and even arrays?

  • It was actually the only way I could find to get the session into a class method to see if the session exists.

  • I understand, you’re sending the class data, I think there’s more practical way.

  • I wanted to save in the session the class object that stores the logged in administrator

  • Face on logon.php in the part where it checks that is locked vc is calling a get parameter, I believe I wanted to call the getName method. Something else, by the way register_globals is enabled?

  • is getNome() right. Here in mine is correct. register_globals = on The session works yes. I already answered this question, check below.

Show 3 more comments

3 answers

1

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

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

The parameter of unserialize() be it string, but there’s a object. That is to say, $_SESSION["admin"] is an already ready object, does not need or can not be deserialized.

Other than that, remove the ?> from your files, when they’re at the end. Avoids problem of spaces after the end of the file, which can be so boring to fix when invisible spaces before <?php.

  • Okay. But I can’t understand, and I ask you to help me to do that, because if all the pages work, why is the object coming only in this one? Nor is it possible to know how to correct, but it can influence the other pages. No?

  • If the other classes work and this one doesn’t, probably what the others do is something like $_SESSION["admin"] = serialize($var);, while in this case is doing something like $_SESSION["admin"] = $var;, that is, without the serialize(). Search for all points that have $_SESSION in your code until you find the different line.

  • I took advantage and launched at the end of the question the logon.php which is where the object is serialized

  • the file is the same for all classes

  • It doesn’t matter that the file is the same. You just showed where $_SESSION["admin"] is used, not where he is filled. Your code is filling this variable in different ways. That’s what you have to look for.

  • I took advantage and launched at the end of the question the logon.php which is where the object is serialized and where it is filled. Not other classes but this page gives error,

  • I looked in logon.php and saw no commands serialize() and even less a type of access $_SESSION["admin"]. You have to look ALL the lines of the system that $_SESSION["admin"] or $_SESSION['admin']. And do something like: if ( is_object($_SESSION["admin"]) ) throw new \Exception();

  • Forgive me, I put the wrong file, I’ve hit the correct logo there

  • So dude, you have to search all the files. Posting the files that work out doesn’t help solve the problem. The mistake says there’s somewhere you do $_SESSION['admin'] = $obj, and that’s the line you have to look for.

  • I can’t find the error. It appears here. Catchable fatal error: Object of class __Php_incomplete_class could not be converted to string in /home/dimoveis/public_html/novo/admin/testaAdmin.php on line 19. But the file of this error is being used via require_once in all files

Show 6 more comments

0

I assume that to solve it would be enough to remove the function unserialize():

$adminLogado = $_SESSION["admin"];

But anyway, I don’t know what’s inside $_SESSION["admin"]. It is therefore impracticable to find a solution with the information you put in the question.

The function unserialize() expects a string as parameter.

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

I assumed that $_SESSION["admin"] should already be serialized with the function serialize(). But due to error message, it is not what is actually happening.

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

To better understand the problem, do a test to see what type of variable:

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

Enter in your question the result of this test.

Probably an array or an Object/stdclass.

  • Hi, thanks for the feedback. Let me be more specific. This is an administrative environment of a website. It has a login screen which is where the serialization happens which is the last file listed in the question. After validation of login, password and lock condition, a new Admins object is created ($type, $name, $login, $password, $blocked); From then on, for each page, I need to validate whether this admin is logged in or not, which I normally do with section. But there is no way to place an object inside a section without being able to be mermalized and there is no way to use that object without being serialized

  • string(222) "O:6:"Admins":6:{s:16:"Adminsidadmins";s:1:"1";s:12:"Adminstype";s:1:"s";s:12:"Adminsnome";s:20:"Carlos Alberto Rocha";s:13:"Adminslogin";s:4:"caca";s:13:"Adminspassword";s:4:"aaaa";s:17:"Adminsbloqueado";s:1:"n"";}"

  • output : Object(__Php_incomplete_class)#1 (7) { ["__Php_incomplete_class_name"]=> string(6) "Admins" ["idAdmins:private"]=> string(1) "3" ["type:private"]=> string(1) "c" ["name:private"]=> string(5) "Test" ["login:private"]=> string(4) "test" ["password:private"]=> string(4) "test" ["blocked:private"]=> string(1) "n" } Warning: unserialize() expects Parameter 1 to be string, Object Given in /home/dimoveis/public_html/novo/admin/testaAdmin.php on line 23 Fatal error: Call to a Member Function getBleased() on a non-object in /home/dimoveis/public_html/new/admin/testaAdmin.php on line 25

  • Another information that may be important is that this only happens in the hosting. Already in localhost the error does not happen!

  • in the logon.php file, you have this: $admin = $AdminsDao->pesquisaAdmin($login, $senha);. In the next line, add var_dump($admin); exit;. This is just for debugging. Then vc can remove. But I believe it will result the same. Because I believe the problem lies within this method $AdminsDao->pesquisaAdmin(). You need to see what’s wrong in there.

  • It turns out that the object is not complete. I already gave the answer with the solution. Thank you for the support.

Show 1 more comment

0

I did it. The solution was:

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

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

It turns out, in order to get ALL the sessional object, it is necessary that session_start() is declared after the require_once of the object class.

Note: This error does not occur on the 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"]);
  ...

Grateful to all opinions regarding doubt.

But if you could use the Singleton standard to instantiate the Testaadmin class once and it would save for each page a copy of the object to not use session would be better. But I searched a lot on the Internet and tried a lot too and nothing.

  • Face honestly what you’re doing is a serious mistake. Save in the session only the registration ID in the bank and when instantiating the object that treats the session you search the database information. Storing an entire object in session is very risky, as sessions can be manipulated in various ways. By storing an ID and searching the database for the information, you restrict access to various information important to system security. Not to mention I wouldn’t have to serialize and deserialize objects all the time, which is a very costly process

  • Um. That’s right. I’m going to change it. It’s easy to change because it’s all OO.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.