【发布时间】:2016-12-02 01:52:30
【问题描述】:
当您点击Login提交按钮时,它只显示“Invalid Token”,因为系统无法识别token。但是,如果我点击 Register 提交按钮,表单就会被提交并处理。
表格代码:
<form method="post">
<div class="field">
<label for="username">Username: </label>
<input type="text" name="username" id="username" autocomplete="off" />
</div>
<div class="field">
<label for="Password">Password: </label>
<input type="password" name="password" id="password" autocomplete="off" />
</div>
<div class="field">
<label for="remember">
<input type="checkbox" name="remember" id="remember" value="on"/> Remember Me
</label>
</div>
<input type="hidden" name="login_token" value="<?php echo Token::generate(); ?>" />
<input name="login" type="submit" value="Login" />
</form>
<hr>
<br>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" value="<?php echo sanitize(Input::get('username')); ?>" autocomplete="off" />
</div>
<div class="field">
<label for="password">Choose a Password</label>
<input type="password" name="password" id="password" />
</div>
<div class="field">
<label for="password_again">Enter your Password Again</label>
<input type="password" name="password_again" id="password_again" />
</div>
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<?php echo sanitize(Input::get('name')); ?>"/>
</div>
<input type="hidden" name="rgstr_tkn" value="<?php echo Token::generate(); ?>" />
<input type="submit" value="Register" name="register"/>
</form>
表单提交时要处理的PHP代码:
if (isset($_POST["login"])){
if(Token::check(Input::get('login_token'))) {
echo "Login!";
echo Input::get('login_token');
} else {
echo 'invalid token';
}
}
if (isset($_POST["register"])) {
if(Token::check(Input::get('rgstr_tkn'))) {
echo "Register!";
echo Input::get('rgstr_tkn');
}
}
Token班级:
class Token {
# Generate a token, and put it into the session/token_name
public static function generate() {
return Session::put(Config::get('session/token_name'), md5(uniqid()));
}
# Check if the token exists
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
Input类:
class Input {
# Check if the POST or GET request is submitted
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
# Get an item from the posted or get field
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
【问题讨论】:
-
能否包含您的配置
-
你能不能也展示一下你的 Session 课程
-
对我来说似乎没问题,检查你是否
session_start();可能你还没有start会话中的会话 -
你能
print_r($_SESSION);看看结果,如果你的会话确实存在于你的数组中,也试试echo Input::get('login_token);看看结果 -
我的意思是你点击登录,
Array()是什么样的?