我创建了一个名为The Recipe Center的localhost网站.在这个网站上,您可以发布食谱并在食谱上发表评论.要发布配方或注释,您必须登录.这是验证登录名称的php文件的代码,或者更确切地说,设置会话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";
}
?>
Run Code Online (Sandbox Code Playgroud)
每当我登录网站时,它都说"您的用户帐户已经过验证,您现在可以发布食谱和评论." 但是,每当我导航到另一个页面并尝试发布食谱或评论时,它都表示我没有登录.这是后配方php文件的代码:
<?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 {
...
}
?>
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释为什么会话cookie在登录页面中设置但在我导航到不同的页面时消失了吗?
您必须在每个页面的顶部启动会话,否则在导航到新页面时将重置会话变量.将此行放在您使用的任何页面的顶部$_SESSION
:
session_start();
Run Code Online (Sandbox Code Playgroud)