Strange problem when overwriting $ _SESSION variable types

I have summarized the essence of the problem as brief as possible:

Simple script:

<?php
session_start();

$_SESSION['user']="logged";

then rewrite

$_SESSION['user']=0;  

and show the contents of $ _SESSION

var_dump($_SESSION);

shows $ _SESSION ['user'] is '0' - sure since it has just been overwritten

BUT now look

if ($_SESSION['user']=="logged"){
    echo "logged";
}
else{
    echo "unlogged";
}

logged is output ....

It seems that changing the type of a variable is only superficial - I have no idea what I'm doing wrong. Do I need to use the comparison === to enable type checking?

+5
source share
2 answers

Exactly you need a strict comparison ===

This is because PHP will try to convert your string to a number, so the "registered" pass will be 0

and then 0 == 0

  • (int) "logged" = 0
  • (int) "1logged" = 1
  • (int) "logged1" = 0

http://www.php.net/manual/en/language.types.type-juggling.php

+3

, :

(int)"logged" = 0

so 0 = 0

if ($_SESSION['user'] === "logged")
0

All Articles