首页 文章

用户通过带有登录凭据(密码和用户名)的$ _POST方法提交表单后如何设置cookie?

提问于
浏览
2

假设用户输入他/她的用户名和密码并单击提交按钮,该按钮在表单上使用$ _POST方法 . 要成功登录,显然用户名和密码必须与我的mysql数据库中的内容相匹配,这是通过一系列“if”语句完成的 . 如果凭据错误,表单和“if”语句必须位于html标记内以显示正确的错误消息 . 在用户名和密码成功满足所有位于html标签内的“if”语句之后,我显然想要设置一个cookie . 但是,我无法在html标签中设置cookie .

/*setcook() function can ONLY be placed HERE before the <html> tags, but that does not work with my php code*/
<html>
<head><title></title><body>

<?php
if (isset($_POST['username']) OR isset($_POST['password']))
{ 
/*bunch of "if" statements go here to confirm the credentials are correct and match what's in the database. if the username and password are correct, all of the "if" statements here are passed, and then i WANT to set a cookie HERE so the user is logged in but i can't*/
}

else echo <<<_END
<form action="login.php" method="post">
Username: <input type="text" name="username"/>
Password: <input type="password" name="password" />
<input type="submit" value="Submit" />"; //this is the form that the user fills out and submits
</form>
_END;
?>

</body>
</html>

但是,setcookie()函数只能在html标记之前使用 . 在我的html代码中的PHP代码中验证所有用户名和密码凭据后,如何设置cookie?

1 回答

  • 1

    你不应该把这样的逻辑与你的HTML混合在一起 . 在发送任何输出之前,将所有PHP用于验证凭据 . 然后,您可以设置所需的任何cookie .

    之后无法设置cookie的原因是cookie被设置为 Headers 的一部分,这些标记在输出开始时发送 . 你可以通过启用输出缓冲来解决这个问题......但是不要这样做 . 这是不好的做法,并不总是在其他服务器上启用,并且有可能减慢头发的速度 .

    我还建议使用PHP会话 . 如果这样做,您可以在任何地方设置数据,因为数据存储在服务器端 . 您必须确保立即启动会话,以便设置cookie并且会话数据可供您的应用程序使用 .

相关问题