代码练习 用户注册登陆与密码加密

时间:2022-11-18 23:51:12

reg.html

<html>
    <head><title>注册</title>
    <meta http-equiv="cotent-type" content="text/html;charset=utf-8">
    </head>
    <body>
        <form action="doaction.php?act=reg" method="post">
            请填写用户名:<input type="text" name="username"><br><br>
            密码:<input type="password" name="password"><br><br>
            <input type="submit" value="注册">
        </form>
    </body>
</html>

login.php

    <head><title>用户登陆</title></head>
    <body>
        <form action="doaction.php?act=log" method="post">
            用户名:<input type="text" name="name">
            密码:<input type="password" name="pwd">
            <input type="submit" value="log">
        </form>
    </body>
</html>

doaction.php

<?php
header('content-type:text/html;charset=utf-8');
session_start();
$act=$_REQUEST['act'];
if($act=='reg'){
        //接收参数
        $name=$_POST['username'];
        $pwd=md5(md5($_POST['password']));
        //注册
        if($name!==null){
            if ($pwd!==null) {
                //链接数据库
                $conn=new mysqli('localhost','root','123','users');
                if(mysqli_connect_errno()){
                    $error=mysqli_connect_errno();
                    $errmsg=mysqli_connect_error();
                    echo "链接不成功:($errno)$errmsg<br/>";
                    $conn->close();
                    exit;
                }else{
                    //echo "链接成功";
                    $conn->query("set names utf-8");
                    $sql="insert into user(name,pwd) values('{$name}','{$pwd}')";
                    $result=@$conn->query($sql);
                    //echo $sql;exit;
                    if(@$result){
                        echo '注册成功,欢迎你'.$name;
                    }else{
                        echo '注册失败';
                    }
                }

                # code...
            }else{
                exit('请填写密码');
            }

        }else{
            exit('请填写用户名');
        }
    }elseif($act=='log'){
        $name=$_POST['name'];
        $pwd=$_POST['pwd'];
        if($name!==null){
            if($pwd!==null){
                $conn=new mysqli('localhost','root','123','users');
                $sql="select name,pwd from user where name='$name' and pwd='$pwd'";
                $result=$conn->query($sql);
                if($result){
                    echo "登陆成功,欢迎回来".$name;
                }else{
                    echo "登录失败";
                    exit;
                }
            }
        }
    }

 $_GET变量接受所有以get方式发送的请求,及浏览器地址栏中的?之后的内容
$_POST变量接受所有以post方式发送的请求,例如,一个form以method=post提交,提交后php会处理post过来的全部变量
而$_REQUEST支持两种方式发送过来的请求,即post和get它都可以接受,显示不显示要看传递方法,get会显示在url中(有字符数限制),post不会在url中显示,可以传递任意多的数据(只要服务器支持)