2014-01-07 29 views
0

我提前道歉久大多代碼問題Cookie不能被加載

當我決定加入「記住我」按鈕,我的登錄表單,我設置的Cookie沒有被加載。我鬆散的,基於我的登錄班級的驗證碼

<?php 

class Login 
{ 
    private $_id; 
    private $_username; 
    private $_password; 
    private $_passmd5; 
    private $_remember; 

    private $_errors; 
    private $_access; 
    private $_login; 
    private $_token; 

    public function __construct() 
    { 
    $this->_errors = array(); 
    $this->_login = isset($_POST['login'])? 1 : 0; 
    $this->_access = 0; 
    if(isset($_POST['token'])) 
    $this->_token = $_POST['token']; 

    $this->_id  = 0; 
    $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username']; 
    $this->_password = ($this->_login)? $this->filter($_POST['password']) : ''; 
    $this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password']; 
    $this->_remember = ($this->_login && $_POST['remember'] == "on")? 1 : 0; 

    if(isset($_COOKIE["username"])) 
     $_SESSION['username'] = $_COOKIE["username"]; 
    if(isset($_SESSION["password"])){ 
     $_SESSION['password'] = $_COOKIE["password"]; 
    } 


    } 

    public function isLoggedIn() 
    { 
    ($this->_login)? $this->verifyPost() : $this->verifySession(); 

    return $this->_access; 
    } 
    public function filter($var) 
    { 
    return preg_replace('/[^a-zA-Z0-9]/','',$var); 
    } 

    public function verifyPost() 
    { 
    try 
    { 
     $excMsg = array(); 
     if(!$this->isTokenValid()) 
     $excMsg[] = 'Oops! We encountered a problem logging you in securely! Prehaps you are trying to log in from a different window? Please try again'; 
     if(!$this->doesUsernameExist()){ 
      $excMsg[] = 'The username field is required!'; 
      } 
      if(!$this->doesPassExist()){ 
       $excMsg[] = 'The password field is required!'; 
      } 
     if(!$this->isDataValid() && $this->doesUsernameExist() && $this->doesPassExist()){ 
      $excMsg[] = 'Only Alpha-Numeric characters are allowed! (A-Z, 1-9)'; 
     } 

     if(!$this->verifyDatabase() && empty($excMsg)) 
     $excMsg[] = 'Invalid Username/Password'; 
     if(!empty($excMsg)) 
      throw new Exception(implode("<br>", $excMsg)); 


    $this->_access = 1; 
    $this->registerSession(); 
    } 
    catch(Exception $e) 
    { 
     $this->_errors[] = $e->getMessage(); 
    } 
    } 

    public function verifySession() 
    { 
    if($this->sessionExist() && $this->verifyDatabase()) 
     $this->_access = 1; 
    } 

    public function verifyDatabase() 
    { 
     require('inc.all.php'); 
     if($suspended){ 
      return false; 
     } 
     $db = new MySQLi('localhost', 'root', '', 'minecraftprofiles'); 
     $sql = "SELECT ID FROM user_login WHERE username = '{$this->_username}' AND password = '{$this->_passmd5}'"; 
     $data = $db->query($sql); 
    if($data->num_rows) 
     { 
     list($this->_id) = @array_values($data->fetch_assoc()); 
     return true; 
     } 
    else 
     { return false; } 
    } 

    public function isDataValid() 
    { 
    return (preg_match('/^[a-zA-Z0-9]/',$this->_username) && preg_match('/^[a-zA-Z0-9]/',$this->_password))? 1 : 0; 
    } 
    public function doesUsernameExist(){ 
     return ($_POST['username'] == '')? 0:1; 
    } 
    public function doesPassExist(){ 
     return ($_POST['password'] == '')? 0:1; 
    } 

    public function isTokenValid() 
    { 
    return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 0 : 1; 
    } 

    public function registerSession() 
    { 

    $_SESSION['ID'] = $this->_id; 
    $_SESSION['username'] = $this->_username; 
    $_SESSION['password'] = $this->_passmd5; 
    if($this->_remember){ 
     $expire=time()+60*60*24*180; 
     setcookie("ID", $this->_id, $expire); 
     setcookie("username", $this->_username, $expire); 
     setcookie("password", $this->_passmd5, $expire);  
    } 
    } 

    public function sessionExist() 
    { 
    return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0; 
    } 

    public function showErrors() 
    { 
    echo "<br><font color=\"#FF0000\">"; 
    foreach($this->_errors as $key=>$value) 
     echo $value."<br>"; 
    echo "</font>"; 
    } 

} 
?> 

以上是一個登錄類,成功保存和載入會議(餅乾)。我以不同的方式執行我的登錄代碼,因此它與ajax兼容。我的當前登錄類:

<?php 
require_once ("../../inc/inc.all.php"); 

if (isset($_POST['username'])) { 
    $GLOBALS['username'] = $_POST['username']; 
} else { 
    echo "Username field is not set!"; 
    die(); 
} 

if (isset($_POST['password'])) { 
    $GLOBALS['passmd5'] = md5($_POST['password']); 
} else { 
    echo "Password field is not set!"; 
    die(); 
} 

if (isset($_POST['remember'])) { 
    $GLOBALS['remember'] = ($_POST['remember'] == "true")? 1 : 0; 
} 

if (!isset($_POST['token'])) { 
    echo "There was a problem logging you in securly! Prehaps you are trying to log in from a different window?"; 
    die(); 
} else { 
    $GLOBALS['token'] = $_POST['token']; 
} 

if (!validToken()) { 
    echo "There was a problem logging you in securly! Prehaps you are trying to log in from a different window?"; 
    die(); 
} 
if (isEmail()) { 
    if (loginEmail()) { 
     save(); 
    } else { 
     echo "Unknown username/password!"; 
     die(); 
    } 
} else { 
    if (loginUsername()) { 
     save(); 
    } else { 
     echo "Unknown username/password!"; 
     die(); 
    } 
} 

function loginEmail() { 
    $sql = "SELECT * FROM cs_users WHERE email = '{$GLOBALS['username']}' AND password = '{$GLOBALS['passmd5']}'"; 
    global $db; 
    $query = $db -> query($sql); 
    if ($query -> num_rows) { 
     list($GLOBALS['id']) = @array_values($query -> fetch_assoc()); 
     $row = $query -> fetch_assoc(); 
     $GLOBALS['username'] = $row['username']; 
     return true; 
    } else { 
     return false; 
    } 
} 

function loginUsername() { 
    $sql = "SELECT ID FROM cs_users WHERE username = '{$GLOBALS['username']}' AND password = '{$GLOBALS['passmd5']}'"; 
    global $db; 
    $query = $db -> query($sql); 
    if ($query -> num_rows) { 
     list($GLOBALS['id']) = @array_values($query -> fetch_assoc()); 

     return true; 
    } else { 
     return false; 
    } 
} 

function save() { 
    if ($GLOBALS['remember']) { 
     // User wants to be remembered, save cookies. 
     $expire = time() + 60 * 60 * 24 * 180; 
     setcookie("id", $GLOBALS['id'], $expire); 
     setcookie("username", $GLOBALS['username'], $expire); 
     setcookie("password", $GLOBALS['passmd5'], $expire); 
    } else { 
     $_SESSION['id'] = $GLOBALS['id']; 
     $_SESSION['username'] = $GLOBALS['username']; 
     $_SESSION['password'] = $GLOBALS['passmd5']; 
    } 
    echo true; 
} 

function isEmail() { 
    if (filter_var($GLOBALS['username'], FILTER_VALIDATE_EMAIL)) { 
     return true; 
    } else { 
     return false; 
    } 
} 

function validToken() { 
    return (!isset($GLOBALS['token']) || $GLOBALS['token'] != $_SESSION['token']) ? 0 : 1; 
} 
?> 

我通過這個類驗證登錄信息:

<?php 

class Login { 

    private $_username; 
    private $_password; 

    private $_access; 
    public $_status; 

    public function __construct() { 
     $this -> _access = 0; 
     if (isset($_SESSION['username'])) { 
      $this -> _username = $_SESSION['username']; 
     } 
     if (isset($_SESSION['password'])) { 
      $this -> _password = $_SESSION['password']; 
     } 

     if (isset($_COOKIE['username'])) { 
      $_SESSION['username'] = $_COOKIE['username']; 
      $this -> _username = $_COOKIE['username']; 
     } 
     if (isset($_COOKIE['password'])) { 
      $_SESSION['password'] = $_COOKIE['password']; 
      $this -> _password = $_COOKIE['password']; 
     } 
    } 

    public function isLoggedIn() { 
     $this -> verifySession(); 
     return $this -> _access; 
    } 

    public function verifySession() { 
     if ($this -> sessionExist() && $this -> verifyDatabase()) 
      $this -> _access = 1; 
    } 

    public function sessionExist() { 
     return (isset($_SESSION['username']) && isset($_SESSION['password'])) ? 1 : 0; 
    } 

    public function verifyDatabase() { 
     require_once (dirname(__FILE__) . "/../config.php"); 
     global $config; 
     $DB_NAME = $config['db']['dbName']; 
     $DB_HOST = $config['db']['host']; 
     $DB_USER = $config['db']['username']; 
     $DB_PASS = $config['db']['password']; 
     $DB_PORT = $config['db']['port']; 

     $db = new MySQLi($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, $DB_PORT); 
     if (mysqli_connect_errno()) { 
      printf("Connection failed: %s\n", mysqli_connect_error()); 
      return false; 
     } 
     $sql = "SELECT ID from cs_users WHERE username = '{$this->_username}' AND password = '{$this->_password}'"; 
     $data = $db -> query($sql); 
     if ($data -> num_rows) { 
      return true; 
     } else { 
      return false; 
     } 
     return false; 
    } 

    public function getUsername() { 
     if (isset($_SESSION['username'])) 
      return $_SESSION['username']; 
    } 

    public function getStatus() { 
     echo $this -> _status; 
    } 

    private function addStatusMsg($msg) { 
     $this -> _status = $this -> _status + $msg + "<br>"; 
    } 

} 
?> 

認爲我的問題縮小到__construct方法的這一部分。

if (isset($_COOKIE['username'])) { 
    $_SESSION['username'] = $_COOKIE['username']; 
    $this -> _username = $_COOKIE['username']; 
} 
if (isset($_COOKIE['password'])) { 
    $_SESSION['password'] = $_COOKIE['password']; 
    $this -> _password = $_COOKIE['password']; 
} 

我通過

// User wants to be remembered, save cookies. 
$expire = time() + 60 * 60 * 24 * 180; 
setcookie("id", $GLOBALS['id'], $expire); 
setcookie("username", $GLOBALS['username'], $expire); 
setcookie("password", $GLOBALS['passmd5'], $expire); 

我在做什麼錯保存的cookies?它一直在竊聽我幾個小時

+0

您應該使用[password_hash](http://www.php.net/password_hash)進行密碼散列。無用的'md5'是密碼散列的一個非常糟糕的選擇。更不用說你的腳本容易受到SQL注入的攻擊,一般認爲它是使用全局變量的不好的做法。 – Mike

+0

如果您只是在沒有任何驗證的情況下執行'$ _SESSION ['username'] = $ _COOKIE ['username']',我就可以設置一個cookie並且可以用任何我想要的用戶登錄。 – Mike

+0

此外,我強烈建議:http://stackoverflow.com/a/477578/811240(請參閱第二部分) – Mike

回答

0

閱讀Common Pitfalls:http://us2.php.net/setcookie。這應該回答你的問題。 $_COOKIE s在下次加載頁面之前不可用。您可以發送header("LOCATION:{$_SERVER['PHP_SELF']}");