undefined variable related to session/cookie
<p>I have a log in form that allows persistent login and regular session. Long story made short, when users are in their account, they can change password, email and stuff. But for that, I need to get their username from their session or cookie first (so I can do the proper SQL query).</p>

<p>I try to do so with this code:</p>

<pre><code>if(isset($_SESSION['username']))
{
    $username = $_SESSION['username'];
}
else
if(isset($_COOKIE['username']))
{
    $username = $_COOKIE['username'];
}
</code></pre>

<p>But if I try to echo $username, I keep getting "undefined variable". <strong>Why is that?</strong></p>

<p>I noticed that if I put a session_start(); at the top. I get the proper username for session but not for cookie of course. <strong>How can I solve that?</strong></p>

<p>The weird part (for me) is that I got the exact same code (well that part) in another page and username isn't undefined.</p>

<p>PS: If something isn't clear or more information is needed, please tell me.</p>

<p><strong>EDIT</strong></p>

<p>I tried this:</p>

<pre><code>    function accountValidation()
{
    if(isset($_SESSION['username']))
    {
        $username = $_SESSION['username'];
    }

    else if(isset($_COOKIE['username']))
    {   
        $cookie = $_COOKIE['username'];
        $explode = explode(' - ', $cookie);
        $username = $explode['0'];
    }
         echo $username;
}

accountValidation();
</code></pre>

<p>And it worked ... So if I put it into a function and then call it, it works?! What is the diference? Why does it need to be into a function for it to work???</p>
