我的目标是检查存储在cookie中的“令牌”的值是否与db中的loginTable表中的值相同。 我能够将cookie的值保存在变量$ token中。我的问题是-> if($ row [“ token”] == $ token)。例如,$ token的值是bm0h8sdigs,而行中的值是bm0h8sdigs,但不输入if。我也尝试了strcmp函数,但是没有用。 if(strcmp($ row [“ token”],$ token)== 0)我也尝试了$ sqlToken =“从登录表中选择* where token ='”。 $ token。 “'”;但这不起作用。
echo $ token;打印出我的cookie中的内容-bm0h8sdigs
<!-- https://github.com/js-cookie/js-cookie This is a library to make handling cookies easier -->
<script>
var token = Cookies.get('token');
</script>
<?php
$token = "<script>document.write(token)</script>";
$var = 0;
include "connectDB.php";
$sqlToken = "SELECT * FROM loginTable";
$resultToken = $mysqli->query($sqlToken);
while($row = $resultToken->fetch_assoc()){
if ($row["token"] == $token){
$var = 1;
}
}
$mysqli->close();
if ($var == 1){
//Token found in db
}
else{
//Token not found in db
}
?>
connectDB.php
<?php
$host = "localhost";
$username = "root";
$password = "usbw";
$database = "test";
$mysqli = new mysqli($host, $username, $password, $database);
$mysqli -> set_charset("utf8");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
loginTable-prnt.sc/u7nidn
Create table loginTable(
loginID int AUTO_INCREMENT,
userID int not null,
token varchar(20) not null,
Constraint PK_loginTable Primary Key(loginID),
Constraint FK_loginTable_userID Foreign Key (userID) References usersTable (userID)
)
答案 0 :(得分:1)
您提供的示例显示$token
拥有值<script>document.write(token)</script>;
当然,比较会失败。
您将javascript变量传递给php的方法将不起作用。
php不能访问javascript范围。尝试通过form
提交来传递变量,或者尝试通过$_COOKIE