开发者

Maintaining a session over multiple pages

I am having trouble designing a way to maintain a session with a cookie across multiple pages. I am doing something very similar to this tutorial. I check the password and username from a splash page, and if it is correct then I set a cookie and fill it with a hash. After that I transfer the user to a different page. If the username/password was not correct then it just redirects back to the splash page.

The main problem I cannot figure out is how to check for the validity of the cookie across multiple pages. As the tutorial suggests, I am doing this in PHP. I suppose posting the ha开发者_JAVA百科sh to the new page is not correct, but I cannot think of any other way to check for the validity of the session/user before loading the page.

Thanks in advance.


That tutorial teaches you to do things in a highly insecure manner. It is incredibly bad to store authentication data of that sort in cookies, especially using such highly obvious names as "username" and "password".

A better (and incredibly more secure than what the "tutorial" teaches) is to use regular PHP sessions. PHP will take care of setting the session cookie for you, and all you do is store your authentication data in the session. At no time will that data ever be sent to the user unless you do it yourself. The only thing that goes back and forth is the session cookie, which is a string of random garbage that "uniquely" identifies the user to PHP.

Once you've got that part done, then you put a small snippet at the top of all your login-required pages, that looks something like this:

<?php

session_start()
if ($_SESSION['loggedin'] !== TRUE) {
   header("Location: http://example.com/login.php");
   echo 'You must log in first';
   exit();
}
?>
<h1>Welcome back, <?php echo $_SESSION['username'] ?></h1>

Unless you're running on a badly misconfigured PHP, or a PHP version from back in the stone ages, there's no way for the remote user to somehow set the 'loggedin' flag without going through your code first.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜