php写登陆模块

    技术2022-05-19  17

    最近在学习php。学了一点关于登陆的东西,写下来备忘。

    新建四个页面,分别命名为login.php   check.php     index.php    error.php。。。

    login页面用表单建立一个登陆页面,不多说了。在代码里用js脚本判断用户名和密码不能为空,为空则重置焦点。代码如下:

    <script type="text/javascript">function jc(){ var userName=document.getElementById("userName"); var userPwd=document.getElementById("userPwd"); if(userName.value=="") {  alert("请输入用户名");  userName.focus();  return false;  } if(userPwd.value=="") {  alert("请输入用户名");  userPwd.focus();  return false; }

    }</script>

     

    check是检查页面,如果密码和用户名正确则重定向到index.php,否则定向到错误页面。代码如下:

     

    <? session_start(); $userName=$_POST["userName"]; $userPwd=$_POST["userPwd"]; if($userName=="admin"&&$userPwd=="123456") {   $_SESSION["userName"]=$userName;  echo "<script type='text/javascript'>window.location='index.php';</script>"; } else {  echo"<script type='text/javascript'>window.location='error.php';</script>"; }

    ?>

    最后说说session验证。session函数是php自带的函数,用于记录用户的登录信息,类似于cookie,但又有所区别。

    我们可以在验证页面定义和使用session,然后在首页再次定义和使用,以达到欢迎莫某的效果。上面再检查里的代码已经有了,下面是首页里的代码:

    <?session_start();

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title></head>

    <body>欢迎<? echo $_SESSION["userName" ]; ?>来到这里

    </body></html>

     

    验证一下,登陆页面输入用户名和密码,如果正确,会跳到首页,显示欢迎某某某,如果错误会跳到错误页面,显示错误。。。。


    最新回复(0)