Forum Moderators: coopster

Message Too Old, No Replies

Change Sign In link to Log Out

I'm using sessions and cookies, but I can't get it to work!

         

max4

4:20 pm on Apr 27, 2009 (gmt 0)

10+ Year Member



Hello,

I'm trying to get the sign in / log out link to change depending on whether the user is logged in or out. The login form action script starts the session and creates a cookie, it looks like this:

<?php
$con = mysql_connect("host","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
session_start();
$username = $_POST["username"];
$userpass = md5($_POST["userpass"]);
$sql = "SELECT username , userpass FROM user WHERE username='$username' AND userpass='$userpass'";
$result = mysql_query($sql);
if (mysql_num_rows($result)!= 1) {
$loginError = 1;
include "login.php";
} else {
$_SESSION['username'] = "$username";
setcookie("member", "logged", time()+1800);
header("Location: profile.php");
}
?>

Then, we have the sign in / log out section found on every page:

<li><?php if(!isset($_SESSION['username'])) echo '<a href="../../ac/login.php">Sign In</a>'; else echo '<a href="../../ac/logout_action.php">Log Out</a>'; ?></li>

So, I'm stating that if the session is not existent then sign in will show otherwise show log out. It works fine on profile.php but it will not work on any other page. I have PHP set to show all errors and no errors are showing up, so it's just not detecting the session. I checked through firefox and both the cookie and session exist. I even tried the following:

<?php if(!isset($_COOKIE['member'])) echo '<a href="../../ac/login.php">Sign In</a>'; else echo '<a href="../../ac/logout_action.php">Log Out</a>'; ?>

And still, it will only work on profile.php and not any other page. Any suggestions?

Thanks,
Max

FourDegreez

4:35 pm on Apr 27, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You must call session_start() before setting values in the session. Also, you are at high risk of hacking by passing user-submitted form values straight into SQL like that! Do a quick search for SQL injection.

max4

4:41 pm on Apr 27, 2009 (gmt 0)

10+ Year Member



Hi FourDegreez,

Thanks for the reply. Where do you want me to call session_start()? I have it in the action script already, and placing one after else still causes the same problem. Please, bear with me; I'm still new to this!

max4

7:22 pm on Apr 27, 2009 (gmt 0)

10+ Year Member



You were correct, FourDegreez; I had to call session_start() in the second portion (the login/log out change). The problem was that when I did this, the link would change to logout and not change back when I logged out which threw me off. It turns out the problem was with my logout script and not the login script. I corrected it and all is well. Thank you.