PHP $_session + MySQL。我究竟做错了什么?

PHP $_session + MySQL. What am I doing wrong?

好的。让我用以下代码解释我遇到的问题。对于它的混乱程度,我深表歉意,我知道这是一团糟,但请耐心等待。我正在尝试为比特币赌博类型的网站创建登录和注册系统。注册系统已经在工作,它使用与下面几乎相同的代码。问题是,我正在尝试解决每次刷新页面时都会自动注销的问题。这就是我尝试使用 cookie、mysql 和 php 会话的原因。一切都列在下面的代码中。它的工作原理是:

•   Encrypts the password (using e.g. AES) with a random key of sufficient length
•   Stores the encrypted password and username in the session
•   Stores the encryption key in a cookie

现在我已经记下了,但我不明白我做错了什么。我已经开始在 class/user.php 上搞砸了很多,我认为问题出在 class/user.php 我不太确定这个问题到底是什么。是因为我忘记在其中包含 Session 了吗?或者是否有一种推荐的方法来检查 mysql 关于 php 会话。我的目标是完成一个不会在刷新时注销的工作登录系统。它会让您保持登录状态 24 小时或直到您单击注销按钮(结束会话)。如果需要我也包含注册函数,那么我可以这样做。但就像我说的,它基本上是完全相同的代码。提前致谢。

也在任何事情之前。这是错误 MySQL Gives + 在登录页面吐出的代码:

SQLSTATE[42000]: Syntax error or access violation: 1065 Query was emptyWelcome
Encrypted: Chyfz4l6k6DbsQkGa+jX2g== 
Decrypted: password

index.php:

<?php 
    include_once("config.php");
?>

<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php $username = $_POST['username']; ?>
<?php $password = $_POST['password']; ?>
<?php
//$_COOKIE["bpuser"];
//$_COOKIE["bpass"];
$secretHash = "6U7T5Sa1f0a7dRUhNila715y088D94XZ";
$encryptionMethod = "AES-256-CBC";  
//To encrypt
$encryptedPassword = openssl_encrypt($password, $encryptionMethod, $secretHash);

//To Decrypt
$decryptedPassword = openssl_decrypt($encryptedPassword, $encryptionMethod, $secretHash);

//Result
//echo "Encrypted: $encryptedPassword <br>Decrypted: $decryptedPassword";
session_start();
$_SESSION["username"] = "".$username;
$_SESSION["password"] = "".$encryptedPassword;

setcookie("site.me", $secretHash, time()+(3600*24), '/', '.site.me');
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Site | Login</title>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <style>
    body {
        padding-top: 70px;
        /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
    }
    </style>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>
<style>

</style>
    <!-- Navigation -->
    <nav class="navbar navbar-default navbar-fixed-top device-fixed-width yamm" role="navigation">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
<style>

</style>
                <a class="navbar-brand" href="/beta/">Site</a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">

                    <li>
                        <a href="#">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
                    </li>
                    <li>
                        <a href="/beta/register">Register</a>
                    </li>
<li>
                        <a href="/beta/login">Login</a>
                    </li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container -->
    </nav>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">


<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <div>
        <!-- /.container -->
    </nav>
<div class="page-header">
<h1><center>Login with Site</center></h1>
</div>
<div class="container-fluid">
    <section class="container">
        <div class="container-page">                
            <div class="col-md-6">          <h3 class="dark-grey">Login to Site</small></a></h3>

                <form method="post" action="">

                <div class="form-group col-lg-12">
                    <label>Username</label>
                    <input type="text" name="username" class="form-control" id="" value="">
                </div>

                <div class="form-group col-lg-12">
                    <label>Password</label>
                    <input type="password" name="password" class="form-control" id="" value="">
                </div>






            </div>

            <div class="col-md-6">


 edited out
</div>
</div>
</div>

<div id="mydiv" style="position: absolute; top:400px; left:530px; width:50px; height:50px;">

<input type="submit" name="login" class="btn btn-primary"></button>
            </div>
</div>
        </div>
    </section>
</div>
<?php 
} else {
    $usr = new Users;
    $usr->storeFormValues( $_POST );

    if( $usr->userLogin() ) {
        echo "Welcome";
$username = $_POST['username'];
$password = $_POST['password'];
//$_COOKIE["bpuser"];
//$_COOKIE["bpass"];
//$secretHash = "6U7T5Sa1f0a7dRUhNila715y088D94XZ";
$secretHash2 = "".$_COOKIE[$site.me];
$encryptionMethod = "AES-256-CBC";  
//To encrypt
$encryptedPassword = openssl_encrypt($password, $encryptionMethod, $secretHash2);

//To Decrypt
$decryptedPassword = openssl_decrypt($encryptedPassword, $encryptionMethod, $secretHash2);





//Result
echo "<br>Encrypted: $encryptedPassword <br>Decrypted: $decryptedPassword";
session_start();
$_SESSION["username"] = "".$username;
$_SESSION["password"] = "".$encryptedPassword;






    } else {
        echo "Incorrect Username/Password"; 
    }
}
  ?>

config.php:

<?php
session_start();
    //set off all error for security purposes
error_reporting(E_ALL);


//define some contstant
define( "DB_DSN", "mysql:host=localhost;dbname=login" );
define( "DB_USERNAME", "root" );
define( "DB_PASSWORD", "removed" );
define( "CLS_PATH", "class" );

//include the classes
include_once( CLS_PATH . "/user.php" );


?>

class/user.php:

<?php


 class Users {
     public $username = null;
     public $password = null;
     public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";

     public function __construct( $data = array() ) {
         if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
         if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
     }

     public function storeFormValues( $params ) {
        //store the parameters
        $this->__construct( $params ); 
     }

     public function userLogin() {
         $success = true;
         try{
            $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            //$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
            mysql_query("SELECT * FROM users WHERE username={$_SESSION['username']} LIMIT 1");
            $stmt = $con->prepare( $mysql_query );
            $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
            $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
            $stmt->execute();

            $valid = $stmt->fetchColumn();

            if( $valid ) {
                $success = true;
echo "validated";
            }

            $con = null;
            return $success;
         }catch (PDOException $e) {
             echo $e->getMessage();
             return $success;
         }
     }

     public function register() {
        $correct = false;
            try {
                $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
                $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

                $stmt = $con->prepare( $sql );
                $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
                $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
                $stmt->execute();
                return "Registration Successful <br/> <a href='/beta/login'>Login Now</a>";
            }catch( PDOException $e ) {
                return $e->getMessage();
            }
     }

 }

?>

好的,这段代码有很多错误(从某种意义上说,我很难理解发生了什么),所以我会写下一些伪代码,希望它能告诉你我所理解的你想要的顺序发生在这个登录过程中。

start session
if not user set
    if cookie set
        decrypt cookie
        check if valid user
        set session to user
    else if form info posted
        check if valid user
        encrypt cookie
        store cookie
        set session to user
    else
        show login form
else
    show protected page

其他一些评论是

  • 您读错了 cookie 值,应该是 'site.me' 而不是 $site.me
  • 'login not submitted' 部分中的大部分代码未使用。
  • 您在登录的部分错过了 setcookie 功能
  • 您可以只使用 new User($_POST) 而不是 storeFormValues 的奇怪构造。

希望对您有所帮助!