登录和会话PHP

时间:2014-03-22 17:30:20

标签: php sql session login system

我在检查会话时遇到一些问题,要访问我需要激活会话的页面。

登录过程:     

    //Connect to mysql server
    require "reservation/connect.php";

    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($str) {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return mysql_real_escape_string($str);
    }

    //Sanitize the POST values
    $login = clean($_POST['user']);
    $password = clean($_POST['password']);

    //Create query
    $qry="SELECT * FROM user WHERE username='$login' AND password='$password'";
    $result=mysql_query($qry);
    //Check whether the query was successful or not
    if($result) {
        if(mysql_num_rows($result) > 0) {
            //Login Successful
            session_regenerate_id();
            $member = mysql_fetch_assoc($result);
            $_SESSION['SESS_MEMBER_ID'] = $member['user_id'];
            $_SESSION['SESS_FIRST_NAME'] = $member['position'];
            session_write_close();
            //if ($level="admin"){
            header("location: admin/dashboard.php");
            exit();
        }else {
            //Login failed
            header("location: index.php");
            exit();
        }
    }else {
        die("Query failed");
    }
?>

验证:     

if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
        header("location: index.php");
        exit();
    } 
?>

即使我从表单登录,页面也不会加载并将我重定向回索引!我做错了什么?我把“require_once('.. / auth.php');”在页面上,但它仍然无法正常工作。

1 个答案:

答案 0 :(得分:2)

这是因为它进入了else语句的一部分,这意味着$result为0或false。

所以原因是查询必须失败..所以像这样添加mysql_error() ..

$result=mysql_query($qry) or die(mysql_error());

要知道确切的原因..


mysql_*)扩展程序自PHP 5.5.0起已弃用,将来会被删除。相反,应使用MySQLiPDO_MySQL扩展名。切换到PreparedStatements甚至可以更好地抵御SQL注入攻击!