signup.php:
<?php
include 'config.php';
if(isset($_POST['submit']))
{
$sql = "INSERT INTO user (username, password) VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if (mysqli_query($con, $sql))
{
setcookie ('AuthVal', 'username='.$_POST['username'].'&loggedIn=true', time() + (3600 * 24 * 30));
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
signin.php:
?>
<?php
include("config.php");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
if(isset($_COOKIE['AuthVal']))
unset($_COOKIE['AuthVal']);
if(isset($_POST['login']))
{
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$sel_user = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user > 0)
{
setcookie ('AuthVal', 'username='.$_POST['username'].'&loggedIn=true', time() + (3600 * 24 * 30));
echo "<script>window.open('index.php','_self')</script>";
}
else
{
echo "<script>alert('Email or password is not correct, try again')</script>";
}
}
?>
的index.php:
<li><a href="mypage.html">My Page</a></li>
<li><a href="signup.php">Sign up</a></li>
<li>
<?php if(isset($_COOKIE['username'])) { ?>
<a href="signout.php">Sign out</a>
<?php } else { ?>
<a href="signin.php">Sign in</a>
<?php } ?>
</li>
感谢您的阅读。这是我到目前为止编写的php代码。我试图做的是#34;登录&#34;选项&#34;退出&#34;在使用登录时在index.php中。当我运行此代码时,&#34;登录&#34;在index.php中保持原样,而不改为&#34;退出&#34;。请帮忙。
首先,我顺便使用了COOKIE吗?
答案 0 :(得分:0)
您将Cookie的名称定义为AuthVal
(setcookie()
的第一个参数):
setcookie ('AuthVal', 'username='.$_POST['username'].'&loggedIn=true', time() + (3600 * 24 * 30));
然后你测试$_COOKIE['username']
:
if(isset($_COOKIE['username'])) { ?>
您必须在所有代码中保留相同的名称,例如:
setcookie ('AuthVal', 'username='.$_POST['username'].'&loggedIn=true', time() + (3600 * 24 * 30));
和
if(isset($_COOKIE['AuthVal'])) { ?>
请注意,它无法识别您的用户。如果要对用户进行身份验证,则必须存储一个秘密值,如随机字符串,并将其存储在cookie中。但这是另一个问题。
答案 1 :(得分:0)
取消预订$ _COOKIE [&#39;某些事情&#39;]无法正常工作,这是你能够解决问题的唯一方法。 Cookie是以负时间或过去时间重新设置的。