设置一个cookie保存登录信息PHP [英] Set a cookie to save login details PHP

查看:149
本文介绍了设置一个cookie保存登录信息PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个典型的登录信息(用户名,密码),也希望包括保存我的信息"复选框.登录表单将其值发布到login_script.php,如果登录成功,则用户将被重定向到网站的主页.

I have a typical login (username, password) and also want to include a 'save my details' check box. The login form Posts its values to login_script.php and if the login is successful, the user is redirected to the main page of the site.

我想使用此方法保存登录详细信息

I'm tying to use this method to save the login details

//Remember Me Function

if(isset($_POST['remember_me'])){

    // Set a cookie that expires in 24 hours
    setcookie("username",$username, time()+3600*24);
    setcookie("password",$password, time()+3600*24);

}

现在从我个人理解,必须在PHP页面之前,任何其他代码的顶部设置执行.

Now from what I understand, setcookie("username",$username, time()+3600*24); must be set at the top of the PHP page before any other code is executed.

我的问题是,我不希望设置Cookie,除非用户已经成功登录,但由于设置cookie的函数被调用中间的脚本登录试验后,将无法正常工作.

My issue is that I do not want to set the cookie unless the user has successfully logged in. However due to the set cookie function being called in the middle of the script after the login test, it will not work.

有什么想法吗? 干杯.

Any ideas? Cheers.

推荐答案

首先:!不要保存在cookie中的密码这是一个非常糟糕的主意安全明智

First of all: do not save passwords in a cookie! This is a very bad idea security-wise.

至于你的问题:有没有办法解决它,你需要有根本没有输出设置您的Cookie之前.有两种方法来实现这一点:

As for your problem: there is no way around it, you need to have no output at all before setting your cookie. There are two ways to achieve this:

<强>解决方案1:登录页面总是重定向

让你的登录请求去一个脚本,设置一个cookie(如果登录成功),然后的总是的用户重定向到另一个页面(如欢迎屏幕,或回到登录页面如果不成功).登录脚本将不会发出任何输出,因此可以重定向之前设置的cookie.

Have your login requests go to a script which sets a cookie (if the login was successful) and then always redirects the user to another page (e.g. a welcome screen, or back to the login page if unsuccessful). The login script will not emit any output, therefore you can set cookies before redirecting.

<强>解决方案2:输出缓冲

输出缓冲在脚本的开头.在检查成功登录后,设置cookie 第一并用类似 .

Start output buffering at the beginning of your script. After the check for successful login, set the cookie first and then stop output buffering with something like ob_end_flush.

我个人考虑溶液#1是在功能更优雅和优越性.

Personally I consider solution #1 to be more elegant and superior in function.

这篇关于设置一个cookie保存登录信息PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆