Samuel Meddows Samuel Meddows - 1 year ago 87
PHP Question

Set a cookie to save login details 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


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


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.

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?

Jon Jon
Answer Source

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

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:

Solution 1: the login page always redirects

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.

Solution 2: output buffering

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.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download