在用户登录网站时尝试将用户名另存为cookie。
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM tblmember WHERE Username='$username' AND Password='$password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) {
$cookie_name = "user";
$cookie_value = $results;
setcookie($cookie_name, $cookie_value);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
//set username as a cookie & then use that to access the user pages.
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
header('location: profile.php');
}else {
array_push($errors, "Wrong username/password combination");
echo "Cookie named '" . $cookie_name . "' is not set!";
}
}
}
我尝试对此进行测试,并且首次使用:$ cookie_value =“ lol”;然后我将其切换为$ cookie_value = $ results;保存更改并从Google chrome中删除该Cookie。然后,我尝试再次在chrome中重新打开该页面,以发现根本没有设置cookie。
答案 0 :(得分:1)
setcookie
的第二个参数必须是字符串。您正在向它传递mysqli::result
对象。您需要从查询中获取结果,然后使用类似serialize
的形式将结果转换为字符串,然后可以将其存储到cookie中。例如:
if (mysqli_num_rows($results) == 1) {
$row = mysqli_fetch_assoc($results);
$cookie_name = "user";
$cookie_value = serialize($row);
setcookie($cookie_name, $cookie_value);
// ...