0

I want to add remember me option to my login functionality, When I set remember me option without redirecting user to his access success page, the cookie stored perfect, but the issue is when I uncomment the redirection. When user attempt to login it redirect and bypass the process to store cookies. How can I fix this issue?

public function login(){
    $username = $this->request->getPost('username');
    $password = $this->request->getPost('password');

    $user = $this->model->getLoginData($username); 
    $rowCount = count([$user]);

    if($user){
        if (password_verify($password, $user->password)){
            //store session data
            $this->auth->userSession($user);

            //remember me 
            if(!empty($this->request->getPost("remember"))){
                $cookie_hash = md5(uniqid()."sghsgd876mbjb");
                set_cookie('hash_cookie', $cookie_hash, 36000 );
            }else{
                set_cookie('hash_cookie', '');
            }  

            return redirect()->to('/manager');               
        }
    }
}
ven
  • 185
  • 1
  • 18

2 Answers2

1

You should try using the Codeigniter helpers instead of set_cookie($cookie);

Here you can read more - LINK

try sending cookies with this function:

// Copies all cookies from global response instance
return redirect()->back()->withCookies();

for more details see docs LINK

  • Thanks Armin, I have tried the solution you gave me, but still I'm getting the same result. The issue here is caused by redirection. Instead of reading the cookie storage script it jump to the redirection, So when I remove redirection the cookies stored successfully. – ven Aug 11 '21 at 22:38
  • try this one it should do the job for you. – 丹尺爪工れ Aug 12 '21 at 08:34
  • Since I want to save remember me cookie the redirection with data will not be a good approach. Thanks @Armin – ven Aug 12 '21 at 08:52
0

You must set cookie path to / to work for all paths, not just current one.

set_cookie('hash_cookie', $cookie_hash, 36000, '/' );

As I read on this post How can I set a cookie and then redirect in PHP?

Jonathan A
  • 40
  • 5
  • I have tried that but still didn't save the cookie, but when I remove redirection it store the cookie. I didn't figure out why is not working. – ven Aug 09 '21 at 07:49