Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `if (isset($_SESSION))` and `if ($_SESSION)`?

I've noticed that frequently people simply write

<?php  if($_SESSION['username']) {...} ?>

while I have been using:

 <?php if(isset($_SESSION['username'])) {...} ?> 

Could someone explain the difference when checking if a variable is set (that's what I'd be using it for)?

like image 272
d-_-b Avatar asked May 07 '12 23:05

d-_-b


People also ask

What is if isset ($_ POST?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What is Isset session?

isset is a function that takes any variable you want to use and checks to see if it has been set. That is, it has already been assigned a value. With our previous example, we can create a very simple pageview counter by using isset to check if the pageview variable has already been created.

What is PHP session_start () and Session_destroy () function?

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. Note: You do not have to call session_destroy() from usual code.

How do you know if a variable is set in a session?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.


1 Answers

In PHP, if a variable does not exist (is "unset") then PHP will spit out an E_NOTICE error, create the missing variable, and assign it to NULL.

If you do not want your scripts filled with annoying error messages that leak information about your server and script - then use isset() to test before trying to access a value.

Basically, you're asking PHP to get username out of $_SESSION and PHP is like, "there is no username"!

like image 95
Xeoncross Avatar answered Sep 30 '22 14:09

Xeoncross