본문 바로가기
PHP, Codeigniter

codeigniter4 set_cookie AJAX를 이용한 경우 에러 해결

by beop07 2023. 4. 12.

codeigniter3에서는 정상적으로 작동 되던 set_cookie가 codeigniter4에서 안되어 엄청 애를 먹었다.

포기 직전까지 갔다가 오기가 생겨 밤 늦게까지 codeingiter 명세서를 꼼꼼하게 다시 정독하였고 http responses에서 힌트를 얻어 해결하였다.

 

먼저 set_cookie는 서버측에서 쿠키를 생성하고 클라이언트에게 전송 한다.

하지만 AJAX를 이용해서 해당 컨트롤러에서 관련 로직을 처리하는 경우 CI4에서는 쿠키를 생성만 하고 자동 응답하는 로직이 없는듯해보였다.

 

해답은 $this->response 이다.

 

public function ajaxCookieTest()
{
    if ($this->request->isAJAX() == false) {
        exit;
    }

    $code = $this->request->getPost('code');
    set_cookie('test_cookie_name', $code, 7200);

    return $this->response;
    exit;
}

 

응답 클래스는 $this->response를 통해 응답 클래스를 액세스할 수 있다.

 

 

쿠키 정보를 반환하고 싶을땐 아래와 같이 한다.

 

public function ajaxCookieTest()
{
    if ($this->request->isAJAX() == false) {
        exit;
    }

    $code = $this->request->getPost('code');
    set_cookie('test_cookie_name', $code, 7200);

    // 쿠키 정보 반환
    $response = [
        'success' => true,
        'cookie_name' => $code
    ];
    
    return $this->response->setJSON($response);
    exit;
}

 

아마 보안을 위한 변경이 아닐까싶다. 알고나서 해당 내용으로 검색해보니 ci포럼에 비슷한 내용이 있긴하였다.

 

keywords : codeigniter set_cookie, ajax set_cookie, codeigniter4 AJAX 쿠키저장

반응형

댓글