简体   繁体   中英

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

Okay. Let me explain the issue I am having with the following code. I truly apologize for how disorganized it is and I understand it is a mess but please bear with me here. I'm attempting to create a login and register system for a bitcoin gambling type of site. The register system is already working and it uses pretty much the same code as below. The thing is, i'm trying to fix an issue where everytime you refresh your page you get auto logged out. That is why i'm attempting to use cookies, mysql, and php session. Everything is listed in the code below. How it works is:

•   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

Now I've gotten that down but I don't understand what I am doing wrong. I've started messing around a lot with class/user.php and I think the issue is inside class/user.php I'm not quite sure of the issue through. Is it because i'm forgetting to include the Session inside it? Or is there a reccomended type of way to check with mysql regarding a php session. My goal for this is to accomplish a working login system that does not log you out on refresh. It keeps you logged in for 24 hours or until you click the logout button (which ends the session). If it is needed that I include the register function too then I can do that. But like I said its basically the same exact code. Thanks in advance.

Also before anything. This is the error MySQL Gives + the code that spits out on the login page:

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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb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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();
            }
     }

 }

?>

Ok, there's a lot wrong with this code (in the sense that I have difficulty understanding what happens), so I'll write down some pseudocode that'll hopefully tells you the sequence of what I understand you want to happen in this login process.

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

Some other comments would be

  • You read the wrong cookie value, which should be 'site.me' instead of $site.me
  • Most of the code that is in the 'login not submitted' part is unused.
  • You miss the setcookie function in the part where you're doing the login
  • You can just use new User($_POST) instead of the weird construction with storeFormValues.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM