Search code examples
javascriptphpcodeigniterhttp-headerscodeigniter-4

How to make a controller's method unavailable to Codeigniter's previous_url()


I am dynamically generating a javascript file on my script in a controller method and adding this dynamically generated script in my html just like you would a regular javascript.

In my php code I return

return $this->response
    ->setBody($data)
    ->setHeader('text/javascript')
    ->noCache()
    ->getBody();

$data is a variable that holds the data on the generated javascript file. So far everything works well until I want to use codeigniter's built in previous_url() function then I'm taken to this javascript file file instead of the previous web page.

So far I have tried hacking the CI core and it works. What I did was return false in storePreviousURL() method of Codeigniter.php if the Cache-control response header contains the no-cache or no-store value which I'm setting with the built in CI $response->no_cache() method in the generator script.

What I want to know is if there is a better way to go around this as personally I also advice against hacking the core, but it seems I'm out of options here.


Solution

  • I was having a similar problem, where I had created an image server to serve dynamic sized thumbnails and then that image url would become the previous url for anything that later needed it. For now I am using the recommended way to change the workings of core, without actually changing the core code: by using Events. It seems to have solved the problem.

    I have added this code inside the method that serves the file:

    $prevurl=previous_url(); //a function from the url helper
    \CodeIgniter\Events\Events::on('post_system',function() use ($prevurl){
        \Config\Services::codeigniter()->storePreviousURL(\Config\Services::uri($prevurl,false));
    });
    

    This resets the previous url to whatever it was before calling this method (i.e., before requesting this url).