假设我想创建一个 super 简单的页面,并限制单个用户的 php 访问。假设授权用户知道页面的目录和 url,他是否可以通过 url 栏中的 get
方法手动传递用户名和密码(他知道),并自动检查针对脚本,其中用户名和密码的值将被硬编码?该脚本有一个 if 语句
,如果不为 true,则不会显示内容。可能存在什么缺陷?
网址
http://example.com/admin.php?user=admin&password=1324
admin.php
<?php if($_GET['user'] == 'admin' && $_GET['password'] == '1324')){
// display content here
}else{
echo "You're not authorized to visit this page";
} ?>
场景 2:post
方法
与上述场景类似,在这种情况下,授权用户将在表单中输入用户名和密码,这些信息将在实际的 admin.php
文件中进行处理。将使用类似的 if 语句
,这次使用 $_POST[]
超全局变量来检查输入。
<?php if($_POST['user'] == 'admin' && $_POST['password'] == '1324'){
// display content here
}else{
echo "You're not authorized to visit this page";
} ?>
最佳答案
两者都有各自的缺陷。
如果您使用方法 1,您最终会将传递到 header 的变量保存在页面历史记录中,这意味着有权访问 PC 的任何人都可以搜索并找到它们,从而在此过程中为自己提供访问权限。搜索引擎还可以获取并保存链接,使其向全世界开放。
如果您使用方法 2,您每次访问安全页面时都需要重新发送 POST 数据,这意味着您最终会得到一堆按钮和表单,其中的链接可能会被删除。已经足够了。不过,它确实消除了第一种方法的问题。
解决这两个问题的更好方法是使用 $_SESSION 变量。这基本上允许数据存储在服务器端,同时为用户提供一个可用于控制对数据的访问的“ key ” - 默认情况下,该 key 存储在 cookie 中。
一个示例用法是:
//Say the user is "admin", and the password is "1234"
//This data could be used to 'log in' via post.
//First of all we start the session, and check to see if the user is logged in
//If the user has the session active, they'll have a cookie on their PC which links to it
session_start();
if ($_SESSION['login']==true || ($_POST['user']=="admin" && $_POST['pass']=="1234")) {
//If they already have a session, give them access.
//If not, check for posted UN & PW and if correct, give access.
$_SESSION['login']=true; //Set login to true in case they got in via UN & PW
//Do stuff for when logged in
}
else { //Not already logged in, not sent a password
//Give the user a login form redirecting to this page.
}
这样做的好处是:
- 用户端未存储密码
- 浏览器关闭时 session key 就会过期
- 密码仅通过互联网传递一次
关于php - 简单的单用户登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117574/