如何限制用户在未登录的情况下进入页面

时间:2011-10-26 18:53:26

标签: php session restrict

我使用会话来记录用户,所以基本上用户存储在会话中。我使用什么代码粘贴到我的以下文件中,这样用户就无法访问该页面,除非他/她已登录。

    <?php
session_start();

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cook It Dot Com</title>
<link href="../style.css" rel="stylesheet" type="text/css" />
</head>
<body><div id="wrap">
<div id="header"></div>
<div id="nav">
            <ul id='menu'>
             <li><a href="../usersloggedin/starters.php" >Starters</a></li>
            <li><a href="../usersloggedin/mains.php" >Mains</a></li>
            <li><a href="../usersloggedin/vegeterian.php" >Vegeterian</a></li>
            <li><a href="../usersloggedin/desserts.php">Desserts</a></li>
            </ul>

            <ul id="rightmenu">
           <li> <a href="logout.php">Logout</a></li>

            </ul>


</div>


<div id="content">
  <div id="info" align="justify"><FONT COLOR="white">
   My Account - 
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ".$_SESSION['myusername'];
}
?>
<hr />
<br /> Upload Your Recipes<br /><br />

<a href="../upload/uploadstarter.php">Upload Starter</a>
<a href="../upload/uploadmains.php">Upload Mains</a>
<a href="../upload/uploadvegeterian.php">Upload Vegeterian</a>
<a href="../upload/uploaddessert.php">Upload Desserts</a>

<br /><br />Edit/Delete Your Recipes<br/><br/>

<a href="../editdelete/editstarters.php">Starter</a>
<a href="../editdelete/editmains.php">Mains</a>
<a href="../editdelete/editvegeterian.php">Vegeterian</a>
<a href="../editdelete/editdesserts.php">Desserts</a>



</div></div>
<div id="footer"><div id="footerinfo" align="center">Copyright Cook It Dot Com 2011 - Designed By Jahedul Hussain - </a></div></div>
</div>
</body>
</html>

非常感谢!

2 个答案:

答案 0 :(得分:3)

这样的东西
if(!isset($_SESSION["user"]))
{
    header("Location: homepage.php");
}

基本上,如果没有用户会话重定向到主页。

答案 1 :(得分:1)

exit()die()函数,或者,如果要显示某些内容,则为包含HTML的简单if语句。 E.g。

<?php if($logged_in) { ?>
<p>You are logged in!</p>
<?php } else { ?>
<p>You're not logged in. Go to the login page.</p>
<?php } ?>