PHP学习日记1-使用php无需数据库的一个登录注册完整实例
学习php也有四个月了,用基础知识来做一个登录注册
本篇环境:apache+php5.6 ; 原理:目录和MD5加密的密码,COOKIE
用到了两个文件:index.html 和 request.php 其中request.php可以自由设定跳转的目的,代码中已标注
index.html部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <html> <head> <title>Login and register by vanllaocap</title> <meta charset="utf-8"> </head> <body> <h3>未注册的用户会自动注册</h3> <form action="request.php" method="post"> <label>用户名</label> <input type="text" name="username" required /> <label>密码</label> <input type="password" name="password" required /> <button type="submit">登录</button> </form> </ body> </html>
|
接下来是request.php部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <?php echo '<style>a{ text-align: center; }</style>'; $username=$_POST['username']; $password=$_POST['password']; error_reporting(0); //避免mkdir失败的warning if(isset($username) and isset($password)){ $account = mkdir('./'.$username); if($account){ //创建成功即为没有注册 $dir='./'.$account.'/'; $file_password=fopen($dir.md5($password).'.txt','w'); fwrite($file_password,'keep'); fclose($file_password); echo '<a href="./index.html">注册成功,立即登录</a>'; exit; }else{ if(file_exists('./'.$username.'/'.$md5($password).'.txt')){ setcookie('username',$username,time()+10086,'/'); setcookie('password',md5($password),time()+10086,'/'); echo '<a href="你想要的跳转链接">登录成功啦</a>'; }else{ echo '<a href="./index.html">用户名或密码错误</a>'; exit; } } }else{ echo '<script>alert("用户名和密码不存在")</script>'; echo '<a href="./index.html">立即登录</a>'; exit; } ?>
|
那么如何调用这个cookie呢?这里我给出一个最简单的办法
在用户中心之类的地方加入这么几行代码
1 2 3 4 5 6 7 8 9
| <?php if(isset($_COOKIE['username']) and isset($_COOKIE['password'])){ //不做操作,正常展示用户中心 }else{ //跳转,exit防止没法跳转 header('Location:./index.html'); exit; } ?>
|
当然,这种方式不如数据库来的好,仅供学习,谢谢