'Set Header in CodeIgniter 4
Hye guys. Just need a help!!! When I was using ci3 so I faced an issue when user clicked browser back button, that's show " resubmit the form", so I solved that issue after setting header in ci3. Now I upgrade my site ci3 to ci4 and again I m facing same issue. Can anyone plz convert this code in CI4?
CI 3 code in Controller construct
$this->output->set_header('Last-Modified:' . gmdate('D, d M Y H:i]') . 'GMT');
$this->output->set_header('Cache-Control: no-cache, must-revalidate');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0', false);
$this->output->set_header('Pragma: no-cache');
CI 4 code in BaseController
$response->setHeader('Last-Modified',gmdate("D, d M Y H:i").'GMT');
$response->setHeader('Cache-Control', 'no-store');
$response->setHeader('Cache-Control', 'no-cache');
$response->setHeader('Cache-Control', 'must-revalidate');
$response->setHeader('Cache-Control', 'post-check=0');
$response->setHeader('Cache-Control', 'pre-check=0');
$response->setHeader('Pragma','no-cache');
$response->setHeader('Cache-Control', 'no-cache');
In CI 4 it is not working. Any help will be appreciated.
Solution 1:[1]
Finally i got the solution and its working fine for me. i have just put these lines in BaseController.
$response->removeHeader('Cache-Control');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
Solution 2:[2]
You don't need to remove Cache-Control and use "native" header to assign it again. I don't recommend this way unless you know exactly what you do and you should be confortble with the execution flow of responses mechanism in codeigniter or any other framework to avoid one of must heavy 500 errors .
Also in the your primary code you maybe overrid the value of cache controle again and again.
If you dealing with the same header name CI4 provide special method for that. You set the header name and value then you apprend values as many as you need. **Use semicolon only when you finish apprending values beacause you risk to overrid old value and this is mistakes in your code please follow the documentation **
You have to change your code like this:
For the same Header name use appendHeader method
$this->response->setHeader('Cache-Control', 'no-cache')
->appendHeader('Cache-Control', 'exemple .. post-check=0, pre-check=0...') ->appendHeader('Cache-Control', 'option 2') ->appendHeader('Cache-Control', 'option 3');
For other headers:
$this->response->setHeader('Last-Modified',gmdate("D, d M Y H:i").'GMT')
->setHeader('Header-Name-1', 'headear value') ->setHeader('Header-Name-2', 'headear value') ->setHeader('Header-Name-3', 'headear value') ->setHeader('Header-Name-4', 'headear value;');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mehran Sarwar |
Solution 2 | Aisthesis Cronos |