我有一个网页,该网页在客户登录时在客户端计算机上创建一个名为“令牌”的cookie,并且内部带有一个随机值。该cookie是从单独的登录页面创建的,因此不包含在此处,因为该cookie已在没有问题。
然后,我将客户端计算机中的cookie令牌值与SQLite3数据库中的令牌值进行匹配。如果两者都匹配,我将从令牌的同一行中选择客户的电子邮件。
当前,如果cookie令牌的值和数据库令牌符合预期,则此方法有效。但是我很难弄清楚两个令牌都不匹配的方式,因此不会显示任何电子邮件。确切地说,我遇到了问题;
if(!$email)
代码区域,因为我不知道如何检查是否没有电子邮件要退回。
这是我拥有的全部代码,请注意,$url
和$db
之类的变量已经从我包含的外部*.php
文件中传递了。
<?php include 'root.php';?>
<?php include ''.$root.'/database.php';?>
<?php
$token=$_COOKIE["token"];
$auth = $db->query("select email, token from users where token='$token'");
if(!isset($token)){
header('location: '.$url.'/login');
}
else {
while ($row = $auth->fetchArray()){
$email=$row['email'];
if(!$email){
echo "Didn't find any emails matching with the current cookie.";
}
}
}
?>
答案 0 :(得分:2)
解决方案可以是:
$token = $_COOKIE["token"];
// Why execute a query if token is not set?
if(!isset($token)){
header('location: '.$url.'/login');
exit();
}
$auth = $db->query("select email, token from users where token='$token'");
// `fetchArray` fetches you row of FALSE if there are no rows.
$row = $auth->fetchArray();
if ($row) {
$email=$row['email'];
} else {
echo "Didn't find any emails matching with the current cookie.";
}
答案 1 :(得分:1)
如果您的fetchArray()
方法返回结果,则$row
将始终是真实值。您可以改为检查$row
的值是否为真,因为没有返回结果的查询会使fetchArray()
返回false
。您还检查是否设置了先前定义的变量 。您应该检查是否设置了cookie,并检查了exit
调用之后的header()
。您也不需要像这样进出PHP,除非您进行了PHP无法解析的操作-
<?php
include 'root.php';
include $root.'/database.php';
if (!isset($_COOKIE["token"])) {
header('location: '.$url.'/login');
exit;
}
$token = $_COOKIE["token"];
$auth = $db->query("SELECT email, token as cnt FROM users WHERE token='$token'");
$row = $auth->fetchArray();
if ($row) {
// Email exists! Use $row['email'] and $row['token']
} else {
// No rows matching the condition
}