php cookies不起作用

时间:2016-01-02 18:50:16

标签: php cookies missing-cookies

在设置cookie之后,我关闭网站并重新输入。我在浏览器选项中检查了cookie,我只在我的网站的cookie中存储了sessionid。

以下是代码:

<!DOCTYPE html>
<html>
<?php
    require "D:/xampp/htdocs/Form_DB/Classes/ConnectionToDB.php";
    require 'D:\xampp\htdocs\Form_DB\Classes\functionsMainPhp.php';

    session_start();


    if(isset($_POST['LoginSubmit'])){
        if(isset($_POST['LoginName']) and isset($_POST['LoginPass']) and validateNamebox($_POST['LoginName']) and validatePassword($_POST['LoginPass'])){
            $loginName = $_POST['LoginName'];
            $loginPass = $_POST['LoginPass'];
            $db = ConnectionToDB::getInstance()->getConnection();
            $query = $db->prepare("select count(*) as count from account where Name=? and Pass=?");
            $query->execute(array($loginName,$loginPass));
            while($rows  = $query->fetch(PDO::FETCH_ASSOC)) {   
                    if ($rows['count'] == "1") {
                        $_SESSION['IsSignedUp'] = true;
                        if($_SESSION['IsSignedUp'] and isset($_POST["LoginRemember"])){
                            setcookie($CookieName, $loginName, time() + (86400 * 30), "/"); // 86400 = 1 day
                        }
                        header('Location: MainForm2LoggedIn.php');
                    }else{
                        $_SESSION['IsSignedUp'] = false;
                        echo("Wrong username or password"); 
                    }
            }
        }else{
            echo("Invalid username or password"); 
        }
    }
?>
<head>
<link rel="stylesheet" type="text/css" href="ProjectCSS.css">
<title>Login Form!</title>
</head>

<body id = "LoginBody">


<form method = "post" action = "" class = "Login" >
<input class = "Login" type = "text" name = "LoginName" placeholder = "Username" style = "height:3em ; width:26.5em">
<?php if(isset($_POST['LoginName']) and (!validateNamebox($_POST['LoginName']))){
        echo "Name must contain characters and white spaces only";
    }
?>
<br>
<input class = "Login" type = "text" name = "LoginPass" placeholder= "Password" style = "height:3em ; width:26.5em">
<?php if(isset($_POST['LoginPass']) and (!validatePassword($_POST['LoginPass']))){
        echo "Password must contain characters and digits only";
    }
?>
<br>
<input class = "Login" action = "" type = "submit" name = "LoginSubmit" value = "Sign In" style = "height:2.9em ; width:28.5em" >
<br>
<div class = "LoginRemember">Remember me: <input type = "checkbox" name="LoginRemember" ></div>
<div class = "NoLoginGoReg">New user?: <a href="RegistrationForm.php">Sign up here!</a></div>
</form> 


</body>

</html>

1 个答案:

答案 0 :(得分:1)

在向客户端发送任何内容之前,您必须发送cookie(setcookie)(删除顶部的<!DOCTYPE html><html>)。同样适用于header命令,该命令仅在任何内容之前发送时才有效。