helson赵子健 2013-09-18 02:56 采纳率: 0%
浏览 959

一段用户验证的PHP代码,就是验证不成功

<?php
$user=$_POST['user'];
$password=$_POST['password'];
$conn=mysql_connect("localhost","root","123456");
if(!$conn){
die("连接失败".mysql_erron());
}
//设置编码
mysql_query("set names utf8",$conn) or die("编码设置失败");
//选择数据库
mysql_select_db("emplpoyadmin",$conn)or die(mysql_errno());
//对比用户名
$sql="select password from employ where 'user'='$user'" ;

//获取数据
$res=mysql_query($sql,$conn);
//密码验证
if ($row = mysql_fetch_assoc($res)) {
    if ($row['$_password']==md5($password)) {
        header("Location:empManage.php");
        exit();
        }
    } 

    header("Location:denglu.php?errno=1");
    exit();
    mysql_free_result($res);
    mysql_close($conn);

php?>

这段是自己写的用户名密码验证代码,但是密码输入正确后验证页面始终是白板,也不跳转,求救。

  • 写回答

1条回答

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-02-16 13:47
    关注

    该回答引用ChatGPT

    首先,您的代码存在一些错误和潜在的安全隐患。mysql_*函数已经被废弃,建议使用mysqli或PDO来连接数据库并执行查询。此外,您的代码容易受到SQL注入攻击。建议使用参数化查询来避免这种情况。


    在您的代码中,密码验证部分可能存在一些问题。具体来说,以下行可能会导致问题:

    if ($row['$_password']==md5($password)) {
    

    应该将 $_password 改为 password ,因为您在SQL查询中选择的列名是 password 。此外,建议在查询之前对用户输入的密码进行处理,例如剥离不必要的空格、特殊字符等。


    另外,建议在条件语句中使用严格的比较运算符(例如 === 或 !== ),以避免类型转换问题。


    最后,您的代码似乎存在一些控制流问题。mysql_free_result() 和 mysql_close() 函数应该在 if 语句块之外调用,否则可能会导致无法正常执行。同时,建议使用 die() 或 exit() 函数来结束脚本运行,以避免出现其他未知错误。


    下面是一个修正后的示例代码:

    <?php
    $user = $_POST['user'];
    $password = $_POST['password'];
    
    $mysqli = new mysqli("localhost", "root", "123456", "emplpoyadmin");
    
    if ($mysqli->connect_error) {
        die("连接失败:" . $mysqli->connect_error);
    }
    
    $mysqli->set_charset("utf8");
    
    $sql = "SELECT password FROM employ WHERE user = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s", $user);
    $stmt->execute();
    $stmt->store_result();
    
    if ($stmt->num_rows == 1) {
        $stmt->bind_result($hashed_password);
        $stmt->fetch();
    
        if ($hashed_password === md5(trim($password))) {
            header("Location: empManage.php");
            exit();
        } else {
            header("Location: denglu.php?errno=1");
            exit();
        }
    } else {
        header("Location: denglu.php?errno=1");
        exit();
    }
    
    $stmt->free_result();
    $mysqli->close();
    

    希望能对您有所帮助。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型