【问题标题】:How to "secure" php pages with session_start();?如何使用 session_start();“保护”php 页面?
【发布时间】:2014-03-02 12:45:04
【问题描述】:
我正在网站内创建一个“会员”页面,其中“会员”可以使用已经存在的预定用户名和密码访问此页面。我制作了一个读取“用户名”和“密码”变量的 php 文件,如果值正确,则将用户发送到此“members.php”页面,如果不正确,则将其发送到另一个页面。我的问题是:我怎样才能让“members.php”页面只对已经提交了正确用户名和密码的用户可用,如果用户不在“会话”中,将被重定向到带有访问表单的页面.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'correctusername' AND $password == 'correctpassword')
{
header("location:members.php");
}
else {
header("location:wrong.php");
}
?>
【问题讨论】:
标签:
php
security
session
redirect
cookies
【解决方案1】:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'correctusername' AND $password == 'correctpassword')
{
//apart from session you can use this urlencode () and get on members page with urldecode
header("location:members.php?foo='urlencode($username)'");
}
else {
header("location:wrong.php?foo='urlencode($username)'");
}
?>
【解决方案2】:
您可以尝试将 members.php 页面的所有代码放入一个
if (isset($_SESSION)){
//all code for the page goes here
}else{
// redirect to other page
}
您还可以有一个会话功能,它将根据用户名和密码为成员设置一个布尔值 $member = true,然后您可以检查
if(isset($_SESSION) && $_SESSION['member']{
//all code for the page for view by members only goes here
}else{
redirect to another page
}
【解决方案3】:
类似的东西?:
<?php
session_start();
if(isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn']=='true')){
//the session variable is already set for this user so not needed to check again
header("location:members.php");
exit;
}
else if(isset($_POST['username']) && isset($_POST['password'])){
//if the user is submitting for the first time, check.
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'correctusername' AND $password == 'correctpassword')
{
//setting session so on next visit to this page, they are
//automatically redirected
$_SESSION['loggedIn'] = 'true';
header("location:members.php");
exit;
}
else {
//if posted values are wrong
header("location:wrong.php");
exit;
}
}
else {
//this block evaluates to true if session has not been set and if no
//'username' or 'password' has been posted
}
?>