Set a cookie to save PHP login information

I have a typical login (username, password), and I also want to enable "save my data". Login form. Will register its values ​​for login_script.php, and if the login is completed successfully, the user will be redirected to the main page of the site.

I am contacting this method to save login information

//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); } 

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

My problem is that I do not want to set cookies if the user has not logged in. However, due to the fact that the cookie function, which is called in the middle of the script after the login test, does not work.

Any ideas? Greetings.

+4
source share
2 answers

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

As for your problem: there is no way around this, you should not have any output before setting your cookie. There are two ways to achieve this:

Solution 1: the login page always redirects

Do your login requests go to the script that sets the cookie (if the login was successful) and then always redirects the user to another page (for example, the welcome screen or back to the login page if it was unsuccessful). Logging in to the script will not produce any output, so you can set cookies before redirecting.

Solution 2: output buffering

Run output buffering at the beginning of your script. After checking for a successful login, first set a cookie and then stop output buffering with ob_end_flush .

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

+7
source

This is a very bad practice for storing a password in which users have access (on the client side). Even worse, you did not hash or encrypt the password when storing the password (clients can see the password!)

A good security policy never allows anyone to see the actual password. Except when the code works with it.

Instead, you can do this:

  • Save Password in Session
  • Extend session longer

Or you can instead

  • hash and encrypt password
  • save file entry data on the server
  • give the file a unique name
  • save name in cookie
  • every time you get a cookie with the correct file name, find the file and get the login information.

But I always recommend the first one, because it is easier to implement, and session processing is done using PHP (unless you redefine session processing)

+2
source

Source: https://habr.com/ru/post/1332712/


All Articles