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)?
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.
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.
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.
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.
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
"!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With