简体   繁体   中英

Trying to display the User's username in my Navigation Bar once user is logged in?

I'm getting a syntax error with this bit of PHP:

<?php
if(!empty($_SESSION['user']))
{
    echo '<li class="dropdown">';

    Problem somewhere in here -> echo '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Logged in ('echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8')')<span class="caret"></span></a>'; <-Problem somewhere in here

    echo '<ul class="dropdown-menu" role="menu">';
    echo '<li class="inactive"><a href="account.php">Account</a></li>';
    echo '<li class="inactive"><a href="logout.php">log out</a></li>';
    echo '</ul>';
}
    else{echo '<li class="inactive"><a href="login.php">Log In</a></li>';
}
?>

Hoping someone better than me can spot what's causing the problem?

It is within a Bootstrap drop down menu. If you need more information I'll do my best to answer. Thanks.

It's because you're echoing within an echo. You should concatonate the strings like so:

echo '<a href="#" class="dropdown-toggle" data-toggle="dropdown">Logged in (' . htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8') . ')<span class="caret"></span></a>';

I would recommend using a more sophisticated approach:

function returnContentUserSignedIn($user) {
        return '
        <li class="dropdown">
                <!-- CONTENT -->
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        Logged in ' . htmlspecialchars($user) . '<span class="caret"></span>
                </a>
                <!-- CONTENT -->
        </li>';
}

function returnContentUserSignedOut() {
        return '
        <li class="inactive">
                <!-- CONTENT -->
        </li>';
}

<?php echo ( !empty($_SESSION['user']) ? returnContentUserSignedIn($_SESSION['user']) : returnContentUserSignedOut() ); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM