not sure if I have a unique problem or just haven't been able to hit the right terms on google to find it, but my problem is dealing with an undefined variable and not being able to check it.
Across my site for menus I include a php file with all the menu stuff in it, then echo out the various parts as needed. My problem is that one of the menu options shows the currently logged in user. Of course when not logged in this is not set, which results in the log file being filled with undefined errors.
Here is the structure:
static.php:
<?php
$menu='
<ul class="menu">
<li class="menu"><a href="#">Home</a></li>
<li class="menu"><a href="#">Option</a></li>
</ul>';
$usermenu='
<ul class="usermenu">
<li class="menu"><a href="#">'.$_SESSION['user_name'].'</a></li>
<li class="menu"><a href="#">Change Pass</a></li>
<li class="menu"><a href="#">Logout</a></li>
</ul>';
index.php:
<?php include 'static.php';
echo "$menu";
if ($login->isUserLoggedIn() == 'true') {
echo "$usermenu";
}
if ($login->isUserAdmin() == 'true') {
echo "$usermenuadmin";
}
?>
As you can see, the $_SESSION['user_name']
is within the static file, so if you aren't logged in it isn't set and produces the error.
Normally I would just use if (!session_status() == PHP_SESSION_NONE) {}
, but since it is in the middle, I cant put it in there.
One way to fix it would be to have a separate static file for things like that and only include it if the session is set, but then I would have to go and change the code across many pages and would have to have a separate file for a single entry.
Am I missing something here or is there an easy way to fix this? From what I found online it isn't possible to echo out php code, so that prevents any of the normal ways of fixing it.
EDIT: Solved it, see my answer below!