我进行了登录,设置了一个带有估算电子邮件地址值的cookie,因此在global.php文件中,它使用以下命令存储用户数据数组:
$email = $_COOKIE["PeopleHub"]; $getuserdata = mysqli_query($con, "SELECT * FROM Earth WHERE email='$email'"); $userdata = mysqli_fetch_array($getuserdata, MYSQLI_ASSOC);
cookie尚未设置,我知道这是因为我做了一个测试文件:
echo $_COOKIE["PeopleHub"];
它只是做了一个空白页。
登录代码(设置cookie的位置):
<?php include "global.php"; ?> <h2>Login</h2> <?php echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. "; ?> <br> <br> <?php if(isset($_POST["email"])){ $email = $_POST["email"]; $password = sha1($_POST["password"]); $check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'"); $check = mysqli_num_rows($check); if($check == 1){ setcookie("PeopleHub", $email, 0, '/'); echo "We logged you in!"; } else { echo "We couldn't log you in!"; } } ?> <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post"> Email <input name="email" placeholder="Email Address" required="" type="text"><br> Password <input name="password" placeholder="Password" required="" type="password"><br> <input type="reset" value="Start Over"> <input type="submit" value="Login"> </form>
您必须先设置Cookie, 然后再 发送任何标头。
从手册:
setcookie()定义要与其他HTTP标头一起发送的cookie。与其他标头一样,必须在脚本的任何输出之前发送cookie(这是协议限制)。这要求您在所有输出(包括和标记以及任何空格)之前都先调用此函数。
这意味着如果您希望按原样使用此代码,则需要研究输出缓冲。
<?php ob_start(); echo "Hello\n"; setcookie("cookiename", "cookiedata"); ob_end_flush(); ?>
根据的内容global.php,这 可能 适合您。我所做的只是在setcookie()调用之前删除了所有输出。如果global.php其中包含任何空格或HTML输出,则将不起作用:
global.php
setcookie()
<?php include "global.php"; if(isset($_POST["email"])){ $email = $_POST["email"]; $password = sha1($_POST["password"]); $check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'"); $check = mysqli_num_rows($check); if($check == 1){ setcookie("PeopleHub", $email, 0, '/'); echo "We logged you in!"; } else { echo "We couldn't log you in!"; } } ?> <h2>Login</h2> <?php echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. "; ?> <br> <br> <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post"> Email <input name="email" placeholder="Email Address" required="" type="text"><br> Password <input name="password" placeholder="Password" required="" type="password"><br> <input type="reset" value="Start Over"> <input type="submit" value="Login"> </form>