Forum Moderators: coopster

Message Too Old, No Replies

Unsetting SESSION without checking if its SET

         

smagdy

8:52 pm on Jan 16, 2009 (gmt 0)

10+ Year Member



Hello,

Is it any bad to do unset(SESSION['var'] without checking if it was set or not?

I mean it works and doesnt give any errors, but I just want to make sure!

Thanks

eelixduppy

8:56 pm on Jan 16, 2009 (gmt 0)



If it doesn't exist then you will get warnings in your error log. You don't need that clutter, do you? ;)

smagdy

9:05 pm on Jan 16, 2009 (gmt 0)

10+ Year Member



Thanks,
One other fast question...

If I want to check if a session is filled with any value.

I just check it like this:
if($_SESSION['var'] != '')

So, is there any problem checking it like that without checking if it was SET or not?

register_global is set OFF

Thanks again

coopster

10:37 pm on Jan 16, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Actually, there are no warnings, no errors thrown when unsetting without checking existence.
<?php 
unset($var); // no error
unset($_SESSION['var']); // no error
unset($_SESSION[$var]); // error! $var doesn't exist
?>

smagdy

10:46 pm on Jan 16, 2009 (gmt 0)

10+ Year Member



Yes, I realized that too... I never got errors or warning though am always unsetting without checking!

mcavic

10:51 pm on Jan 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I just check it like this:
if($_SESSION['var'] != '')

That will show a warning if it doesn't exist. This should work though:

if (isset($_SESSION['var'])) {
unset($_SESSION['var']);
}

eelixduppy

10:52 pm on Jan 16, 2009 (gmt 0)



heh, sorry guys. My memory is starting to slip on these things. But just because PHP works like this doesn't mean it is good coding practice. You should always know where your variables are coming from. It won't matter too much here, but it could in other code.