Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange issue when overwriting $_SESSION variable types

I've summarized the crux of problem to be as brief as possible:

A simple script:

<?php
session_start();

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

then overwrite

$_SESSION['user']=0;  

and show $_SESSION contents

var_dump($_SESSION);

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

BUT now watch

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

outputs "logged"....

Seems the change of variable type is only superficial - I've no idea what I'm doing wrong.. Do I need to use the === comparison to include checking the type?

like image 735
Joey Avatar asked Oct 23 '22 10:10

Joey


1 Answers

Exactly, you need to do strict comparison ===

That is because PHP try convert your string in a number so "logged" pass to 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

like image 176
Maks3w Avatar answered Nov 04 '22 00:11

Maks3w