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

时间:2015-04-21 04:18:39

标签: php mysql variables session cookies

好。让我用以下代码解释我遇到的问题。我真的为它是多么混乱而道歉,我知道这是一团糟,但请在这里忍受我。我试图为比特币赌博类型的网站创建登录和注册系统。寄存器系统已经工作,它使用与下面几乎相同的代码。问题是,我试图修复一个问题,每次刷新页面时都会自动注销。这就是为什么我试图使用cookies,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吗?或者是否有一种推荐类型的方式来检查有关php会话的mysql。我的目标是完成一个工作登录系统,不会在刷新时注销你。它使您保持登录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;&nbsp;&nbsp;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p;&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" );


?>

类/ 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();
            }
     }

 }

?>

1 个答案:

答案 0 :(得分:0)

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

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值,该值应该是&#39; site.me&#39;而不是$ site.me
  • &#39;登录中的大部分代码未提交&#39;部分未使用。
  • 您错过了登录
  • 部分的setcookie功能
  • 您可以使用new User($_POST)代替使用storeFormValues的奇怪构造。

希望这有帮助!