Question

Is using isset() a good way to validate whether a user has logged in, and then using unset() when the user logs back out to destroy the variable.

Was it helpful?

Solution

The only type of variable that will hang about during page refreshes is a $_SESSION variable. Now, while you can certainly unset() these and the next page won't be able to see it (hence your code will work), it might actually be a better idea to maintain a variable with a set of values.

This will allow for more freedom and flexibility. For example, if you simply use a session variable as a bool (either it is there, or it isn't) you only have options for on/off.

On the other hand, if you initialize the variable on the first page and then modify the data within it as needed you have much more flexibility with what your code does, for example:

$_SESSION['LoggedIn']='fresh'; 
    // user has just opened the page and not logged in
$_SESSION['LoggedIn']='login'; 
    // We have presented the user the login page at least once.
$_SESSION['LoggedIn']='validated'; 
    // User has successfully logged in

With this approach, you can also quite happily store additional information, such as a user who clicks a link, but that page needs authentication before showing information. The user is of course redirected to the login page, but in the background, we store another session variable that waits until the user has successfully logged in, then triggers an event that will redirect the user back to the page that they originally wanted to see. This is both intuitive for the user as also makes for a friendly interface. Nothing annoys me more than going to a site, logging in and being redirected to the front page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top