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:
<?php
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: