0

Hi,

Below is the code I am having difficulty making work:

public function showLoginOut() {
    if (session==null)
        {
        return '<li><a href="login.php">Login</a></li>';
        }
    else
    {
        return '<li><a href"logout.php">Logout</a></li>';
    }
    }
    *^ Above is a PHP page, which holds functions I can use in a phtml document*


<ul>
                    <li><a href="index.php">Home</a></li>
                    <?php
                    function showLoginOut() {
                    };
                    ?>
                    <li><a href="allstock.php">All Our Stock</a></li>
                    .....
*  ^ Above is part of the phtml page.*

When I run the page there are no errors shown, but in the list there's no Login or Logout. I don't know why. I've tried echo instead of return, but the same thing happens. Any help would be greatly appriciated.

Thank you.

3
Contributors
3
Replies
21
Views
3 Years
Discussion Span
Last Post by Mohamed_26
1

In line 2, you are comparing session to null. However, firstly, there is an error in your code here, as "session" is no PHP language. It should either be $session or $_SESSION. If you want to check if a session has been started, I recommend you use session_id() to check that, instead of just $_SESSION.

Secondly, you are now returning some HTML. I would rather return true or false, and then echo some HTML according to if true or false is returned when you execute the function.

Third, you are not executing your function correctly in your HTML. Instead of executing the function, you are redefining it. You could try this:

<?php
public function isLoggedIn() 
{
    if(!session_id()) {
        // No session ID has been set.
        return false;
    }
    else {
        // Session ID has been set.
        return true;
    }
}
?>

<ul>
    <li><a href="index.php">Home</a></li>

    <?php
    $is_logged_in = isLoggedIn();

    if($is_logged_in) {
        echo '<li><a href="login.php">Login</a></li>';
    }
    else {
        echo '<li><a href="logout.php">Logout</a></li>';
    }
    ?>

    <li><a href="allstock.php">All Our Stock</a></li>
</ul>
0

Thank you for the feedback Minitauros, that's really helpful!

Now I have an issue of calling an undefined function, the function being isLoggedIn(). I don't understand why. It is defined in SessionData.php, where functions are defined. And the .phtml page requires it.

At present the menu has Home, then the error and the rest of the list isn't there.

0

If the functons are defined in another file, you may have to add

require "the name of the file your functions are"

I think that should work

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.