代码改变世界

php通过session判断用户是否登录

2012-02-07 22:18  youxin  阅读(2471)  评论(0编辑  收藏  举报

  首先创建一个函数

<?php
session_start();
function isLoggedIn() {
if (isset($_SESSION[‘user_id’])) {
return true;
}
else {
return false;
}
}//isloggedin
?>





  When you have a page that you want only a logged-in user to see, check at the beginning of the
page to see if she is logged in. Display the page only if the function returns true. In this example, if
the user is not logged in, she sees a message that says the page is restricted. Otherwise, if the user is
logged in, she sees the private page:

<html>
<title>Private Page</title>
<body>
<?php if (!isLoggedIn()) : ?>
<p>Sorry, this page is restricted. </p>
<?php else : ?>
<h1>Welcome</h1>
<p>You are looking at a private page.</p>
<?php endif; ?>
</body>
</html>

   You can use this same logic to restrict access to a part of the page as shown in the following
example:

<html>
<title>Private Information</title>
<body>
<h1>Welcome</h1>
<p>You are looking at the public part of this page.</p>
<?php if (isLoggedIn()) : ?>
<p>And here you see private information</p>
<?php endif; ?>
<p>And here is more public information.</p>
</body>
</html>