开发者

PHP web page does not set SESSION cookie

I made a localhost website called The Recipe Center. In this website you can post recipes and post comments on the recipes. In order to post a recipe or a comment, you must log in. This is the code for the php file which validates the log-in name, or rather, sets the session cookie:

<?php

$con = mysql_connect("localhost", "test", "test") or die('Could not connect to server');
mysql_select_db("recipe", $con) or die('Could not connect to database');

$userid = $_POST['userid'];
$password = $_POST['password'];

$query = "SELECT userid from users where userid = '$userid' and password = PASSWORD('$password')";
$result = mysql_query($query);

if (mysql_num_rows($result) == 0)
{
echo "<h2>Sorry, your user account was not validated.</h2><br>\n";
echo "<a href=\"index.php?content=login\">Try again</a><br>\n";
echo "<a href=\"index.php\">Return to Home</a>\n";
} else
{   
$_SESSION['valid_recipe_user'] = $userid;
echo "<h2>Your user account has been validated, you can now post recipes and comments</h2><br>\n";
echo "<a href=\"index.php\">Return to Home</a>\n";
}
?>

Whenever I log-in to the website, it says that "Your user account has been validated, you can now post recipes and comments." However, whenever I navigate to a different page and try to post a recipe or a comment, it says that I am not logged in. This is the code for the post-recipe php file:

<?p开发者_运维问答hp
if(!isset($_SESSION['valid_recipe_user'])){
echo "<h2> Sorry, you do not have permission to post recipes.</h2>\n";
echo "<a href=\"index.php?content=login\">Please login to post recipes</a>\n";
}
else {
...
}
?>

Can anyone explain to me why the session cookie is set in the log-in page but disappears as I navigate to a different page?


You have to start the session at the top of each page or else session variables will be reset when you navigate to a new page. Put this line at the top of any page in which you use $_SESSION:

session_start();


Are you sure you are getting the cookie in the first place? If you check for the cookie in firebug or chrome or whatever it should show the phpsessionid being the same as you see in your db. If you see that, then you should just be able to check $_COOKIE AND $_SESSION the make sure they are logged in.

Else you need to make sure use cookies is set in your ini.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜