Search code examples
codeignitercookiesdocumentationcodeigniter-4

delete_cookie('name') not working codeigniter 4


I am trying to delete the cookie i create when user logs in but somehow delete_cookie() function is not deleting the cookie i made. I checked the documentation and everything but i cannot get it to work

Here is my code

    public function __construct()
{
    helper('cookie');
}

    public function login() {
    $data = [];
    $session = session();
    $model = new AdminModel();
    $username = $this->request->getPost('username');
    $password = $this->request->getPost('password');
    $remember = $this->request->getPost('agree');

    $rules = [
        'username' => 'required',
        'password' => 'required',
    ];


    if(!$this->validate($rules)) {
        $data['validation'] = $this->validator;
    } else {
        $admin = $model->where('username', $username)->where('password', $password)->first();
        if($admin) {
            $session->set('uid', $admin['id']);

            if($remember) {
                set_cookie([
                    'name' => 'id',
                    'value' => $admin['id'],
                    'expire' => '3600',
                    'httponly' => false
                ]);
            }

        } else {
            $session->setFlashdata('msg', 'Incorrect Username or Password');
            return redirect()->to('admin/login');
        }
    }

    return view('admin/login', $data);
}

public function logout() {
    $session = session();
    $session->destroy();
    delete_cookie('id');

    return redirect()->to('admin/login')->withCookies();
}

Edit: I fixed it. I had to redirect with withCookies();


Solution

  • use this Library

    use Config\Services;

    Services::response()->deleteCookie('id');

    refer this link https://codeigniter.com/user_guide/libraries/cookies.html