如何在php查询中使用$\u COOKIE?
我目前正在用PHP做一个简单的登录系统,写这篇文章的时候如何在php查询中使用$\u COOKIE?,php,mysql,cookies,mysqli,Php,Mysql,Cookies,Mysqli,我目前正在用PHP做一个简单的登录系统,写这篇文章的时候 $sql = "SELECT * FROM logintoken WHERE token ='".$_COOKIE['SNID']."';"; 它没有给出任何结果,即使当我回显$_COOKIE['SNID']时,它吐出了正确的结果。我还检查了数据库,值在“token”行中。那么我如何解决这个问题呢。感谢您阅读本文。这是我的密码: <?php if(isset($_COOKIE['SNID'])){ echo 'Logg
$sql = "SELECT * FROM logintoken WHERE token ='".$_COOKIE['SNID']."';";
它没有给出任何结果,即使当我回显$_COOKIE['SNID']时,它吐出了正确的结果。我还检查了数据库,值在“token”行中。那么我如何解决这个问题呢。感谢您阅读本文。这是我的密码:
<?php
if(isset($_COOKIE['SNID'])){
echo 'Logged in';
echo '<form action="logout.weg.php" method="post">
<button type="submit" name="logout">Press to logout</button>
</form>';
$userid = $_COOKIE['SNID'];
$sql = "SELECT * FROM logintoken WHERE token ='".$_COOKIE['SNID']."';";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0){
while ($row= mysqli_fetch_assoc($result)){
echo $row['user_id'];
}
} else {
echo 'No result';
}
} else {
echo 'Not logged in';
}
?>
要回答您的问题:
- 您应该使用完全转义cookie值
- 问题也可能是您的
代码>。从SQL中删除它。报告说:
不应在语句中添加终止分号或\g 此外,您应该检查MySQL并使用bug输出,例如:
$result = mysqli_query($conn,$sql) or error_log(print_r(mysqli_error($conn),true));
(限定词:这不是最好的方法,但这确实能快速完成任务)
做你想做的事的正确方法: (限定词:你试图做的事情可能不是最好的方式,但这里有一些正确的方法) 请仔细阅读:
- (这是必要的阅读)
$sql
内容,并将其与手写查询进行比较?易于破解的代码:)只需在浏览器上创建一个名为SNID的cookie并登录即可。您不应该使用cookie来控制登录信息。您最应该使用cookies的是记住我的函数。请使用@FluxCoder不正确。对于“记住我”cookies,您需要一个与OP相同的识别令牌。否则就是“记得谁吗?”托德·苏厄尔,是的,我记得。Metalik,我知道,但我还是个业余爱好者,所以我不想让我的代码太复杂,但谢谢你的建议。对于其他人,谢谢大家
/***
* Never trust user data. Including cookies.
* Here assume cookie random token key is any alphanumeric character.
* This key is NOT the password
***/
$userid = $_COOKIE['SNID'];
$useridClean = preg_replace("/[^a-z0-9]/i","",$userid); // clean the cookie value
if($useridClean !== $userid){
die("bad cookie!");
}
/***
* Hash your cookie value
***/
$useridClean = hash('sha256', $userid);
/***
* NOTE: Do NOT append ; at the end of the statement.
* Good practise to check the user is expecting to be "remembered"
***/
$sql = "SELECT username, userid FROM logintoken WHERE token = ? AND
remember_me_flag = 'Y' AND user_banned_flag != 'Y' ";
/***
* Use prepared statements for safety
***/
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->prepare($sql);
$result->bind_param("s", $useridClean);
$result->execute();
$row = $result->fetch_array(MYSQLI_ASSOC);
$result->close();
if($row['userid'] > 0 && !empty($row['username'])){
/***
* Once the user has returned; reasign new token values in both
* The database and the cookie
***/
echo "Hello ".$row['username'];
}
}
else {
echo 'No result';
}