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.

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>

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.