我有一个基于restful服务的网站,我的问题是使用html5验证位于浏览器本地存储中的用户身份验证 token 是否存在。
我使用jQuery将 token 从客户端传递到服务器以验证 token 是否存在,但是如果 token 存在或不存在,则返回的http状态代码始终为200,我不明白为什么。
我的这项工作代码分为两页:一页用于客户端,一页用于服务器。
Home.html
<script type="text/javascript">
//other code
$(document).ready(function(){
localStorage.getItem("tokenMyWebSite");
document.getElementById("tokenhtml").innerHTML = localStorage.getItem("tokenMyWebSite");
if (localStorage.getItem("tokenMyWebSite") === null) {
window.location.replace("index.html");
} else {
var token = localStorage.getItem("tokenMyWebSite");
$.ajax( {
url: 'verify.php',
method: 'GET',
data: {
token: token, /* (backend): (frontend)*/
},
error:function(response){
// Simulate an HTTP redirect:
alert("Token is not present in database");
//localStorage.removeItem("tokenListenMe");
//window.location.replace("index.html");
}
});
}
});
//other code
</script>
验证.php
<?php
require ("debug.php");
$conn = new mysqli('localhost', 'root', '', 'MyWebSite');
$token = $conn->real_escape_string($_GET["token"]);
$sql = $conn->query("SELECT token FROM credenziali where token = '$token' LIMIT 1");
if (!$sql) {
http_response_code(404);
die(mysqli_error());
}
if(mysql_fetch_array($sql) !== false) {
http_response_code(200);
} else {
http_response_code(404);
}
mysqli_close($conn);
?>
最佳答案
您将 mysqli
与 mysql
混合在一起(已弃用)。请注意此处缺少 i
:
if(mysql_fetch_array($sql) !== false) {
将其更改为 mysqli_fetch_array
并将 !== false
更改为 !== null
(因为 mysqli_fetch_array()
失败时返回 null,而不是 false),你应该很好。
关于javascript - 使用 Restful 服务验证网站中数据库表中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59706458/