• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
set_cookie & redirect() didn't work

#1
Hello,

Here is my User controller code. I don't know why the function "set_cookie" didn't work. It redirected to the home page, but it didn't set the cookie in the browser. Please help.

PHP Code:
<?php namespace App\Controllers;

use 
CodeIgniter\Controller;

class 
User extends BaseController
{
 
 public function index()
 
 {
 
   return view('welcome_message');
 
 }

 
 public function login()
    {
 
   $data = [];
 
   if($this->request->getMethod() == 'post')
 
   {
 
     if(!$this->validate([
 
       'username' => ['label' => 'Username''rules' => 'required'],
 
       'password' => ['label' => 'Password''rules' => 'required'],
 
     ]))
 
     {
 
       $data['errors'] = $this->validator->getErrors();
 
     }
 
     else
      
{
 
       set_cookie('login'md5($this->request->getVar('password')), time() + 86400);
 
       return redirect()->to('/');
 
     }
 
   }
        return 
view('login'$data);
    }

 
 public function logout()
    {
 
   delete_cookie('login');
        return 
redirect()->to('/');
    }
 
 
}
 
  
Reply

#2
You should set the cookie on the response object like:

Code:
$this->response->setCookie();
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply

#3
Thanks kilishan . I changed to set the cookie on the response object and it still didn't work with the redirect(). I have to set the header on the response object for redirecting

So, I changed from:
PHP Code:
set_cookie('login'md5($this->request->getVar('password')), time() + 86400);
return 
redirect()->to('/'); 

To:
PHP Code:
$this->response->setCookie('login'md5($this->request->getVar('password')), time() + 86400)->setHeader('Location''/'); 

Also, $this->response->deleteCookie('login') didn't work so I have to use:
PHP Code:
$this->response->setCookie('login''')->setHeader('Location''/'); 

Is this the correct way to do like this?
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.