PHP Flat-file 初学者登录脚本
为初学者创建一个基于文本文件的登录系统。
文章
刚开始接触Web开发吗?想知道如何允许用户登录?想要简单易用,并且使用尽可能少的语言和资源?那么这个登录系统已经被应用在我的多个网站上,并且运行良好。它不使用数据库,非常适合初学者。你需要对HTML和PHP有基本的了解。希望你有所收获!(具备PHP的基础知识,包括如何创建一个Web服务器。)
要点
这个想法是创建一个能够完成任务的登录系统,它限制对页面的访问或显示不同的消息。
代码
所以让我们从注册页面开始。我正在创建一个基本的、极简的HTML网页。你可以随意设计页面外观!
让我们从一个注册网页开始
<html>
<head><title>Simple Sign Up</title></head>
<body>
<form action="cuser.php" method="post">
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Submit Account">
</body>
</html>
没什么特别的,只是一个表单。
现在创建 cuser.php。
<html>
<body>
<?php
if(!isset($_POST['uname']) || !isset($_POST['pass'])){ //Redirect somewhere }
$ourFileName = $_POST['uname'] ."_pass.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle); $fopen = fopen($ourFileName, 'a');
fwrite($fopen, $_POST['pass']);
fclose($fopen);
?>
发生的事情是我们将用户名和 _pass.txt 组合在一起,创建包含密码的文件,并将密码存储在其中。
现在关于登录呢?
嗯,我猜你理解HTML,所以创建一个带有表单的页面,其 action 属性设置为 login.php 或其他内容,method 属性设置为 post。 另外,变量/输入应该为 pass 和 user。将其设置为 get 会允许用户从 URL 栏登录。
这是我们的登录脚本
<?php session_start(); ?>
<html>
<body>
<?php
if(!isset($_POST['uname']) || !isset($_POST['pass'])){
//Redirect somewhere
}
$myfile = $_POST['uname'] ."_pass.txt";
$username = $_POST['uname'];
$postpass = $_POST['pass']; //Above just helps tidy up
$exists = file_exists($myfile);
if($exists){ $file = $myfile;
$fh = fopen($file, 'r');
$pass = fread($fh, filesize($file));
fclose($fh); //Above checks if exists and sets pass as the real password
}
if(($exists) and ($pass == $postpass)){
//Above checks if the real pass is equal to the entered pass
$_SESSION['user'] = $username;
$_SESSION['logged'] = "yes";
//Above sets the session which is used to do stuff with the profiles (up next)
echo "Login Succesfull.";
}else{
print "Username or password was incorrect.";
}
?>
</body>
</html>
上面的注释应该能帮助你理解。
所以你想限制对页面的访问,如果他们没有登录?好吧,只要你继续阅读即可。
这里有一些带有注释的代码,可以帮助你限制或在用户登录或未登录时执行某些操作。
<?php session_start();
//This allows use of session variables
?>
<html>
<head>
<?php
if((isset($_SESSION['logged']))
and
($_SESSION['logged'] == "yes")){
// DO NOTHING
}else{
//Below alerts the user if they aren't logged in. It also makes the window go back.
echo <<<EOF
<script>
alert("Sorry you must be logged in to view this.");
window.history.back();
</script>
EOF;
}
?>
</head>
<body>
Stuff only users can see
</body>
</html>
你的登录系统应该可以工作了!
讨论的主题
你学会了如何创建一个登录系统吗?这有帮助吗?你用这个方法创建了新的网站吗?如果是,请告诉我们!
历史
- V2 版本 - 添加了建议使用
isset()
来确保已发送表单数据 - V3 版本 - 代码的小修复
- V4 版本 - 上述小修复的进一步修复(哈哈)