我提前为很长时间的代码问题道歉
当我决定在我的登录表单中添加“记住我”按钮时,我设置的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>";
}
}
?>
以上是一个成功保存和加载会话(和cookie)的登录类。我以不同的方式执行我的登录代码,因此它与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'];
}
我通过
保存Cookie// 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);
我做错了什么?它一直困扰我几个小时
答案 0 :(得分:0)
在http://us2.php.net/setcookie阅读Common Pitfalls:
。这应该回答你的问题。在下次加载页面之前,$_COOKIE
不可用。您可以发送header("LOCATION:{$_SERVER['PHP_SELF']}");