PHP实现文件数据登陆注册功能
- 保存数据文件user.txt,数据如下所示。
admin1|00000@.com|12345
admin2|a2asd@.com|14534
admin3|12222@.com|12345
admin5|11111@.com|12345
- 首页实现代码,包括登录和注册两部分,index.php代码如下:
<?php
require_once "./function.php";
$a = @$_GET['a'];
if($a == 'r'){
?>
<form action="" method="post">
<p>用户名:<input type="text" name="username"></p>
<p>邮 箱:<input type="text" name="email"></p>
<p>密 码:<input type="password" name="password"></p>
<p><input type="submit" name="注册"></p>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$res=register($username,$email,$password);
if($res>0){
echo "用户名邮箱或密码为空";
}else if($res<0){
echo "用户信息添加失败请联系管理员";
}else{
echo "添加成功<script>window.location.href='index.php?r=login';</script>";
}
}
}else if($a=='login'){
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$password = $_POST['password'];
$res=checkLogin($email,$password);
if($res=='0'){
echo "登陆成功";
}else{
echo "登录失败";
}
}else{
?>
<form action="" method="post">
<p>邮 箱:<input type="text" name="email"></p>
<p>密 码:<input type="password" name="password"></p>
<p><input type="submit" name="登录"></p>
</form>
<?php
}
}else{
echo "没有这种操作";
}
- 登陆注册两个主要函数的实现,function.php代码如下所示:
<?php
function register($username,$email,$password){
if($username==" ")
return 1;
if($email==" ")
return 2;
if($password==" ")
return 3;
$fp = fopen("user.txt","a+");
if(!$fp){
return -1;
}
if(!fwrite($fp,"\r\n$username|$email|$password")){
return -2;
}
fclose($fp);
return 0;
}
function checkLogin($email,$password){
if($email=="")
return 1;
if($password=="")
return 2;
$fp = fopen("user.txt","a+");
if(!$fp){
return -1;
}
$isLogin=false;
while(!feof($fp)){
$line = fgets($fp);
$line=substr($line,0,strlen($line)-2);
$info = explode('|',$line);
if($info[1]==$email && $info[2]==$password){
$isLogin=true;
break;
}
}
fclose($fp);
return $isLogin?0:-2;
}