-1

I need to make a redirect in PHP under a condition and I would like to do that in the mymodulename.module file instead of using .htaccess (don't ask why). I've found a code like

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('/path/to/redirect');
$response->send();
return;

But I don't find which function I should use in my module to run the code. I mean something like:

function whenPageIsRequested() {
    $response = new RedirectResponse('/path/to/redirect');
    $response->send();
    return;
}

What the correct name of the function to use as the "wrapper"?

8
  • Looks like you found the right question but didn't scroll down enough - see drupal.stackexchange.com/a/215428/2800 for an example of redirecting via an event subscriber
    – Clive
    Aug 17 at 14:22
  • @Clive I meant that page, but I don't understand what is the $path argument? If it's the current page path as the condition under which the redirect should work, then why it's passed to new RedirectResponse() as the redirect path?
    – stckvrw
    Aug 17 at 14:36
  • You mean the path passed to the RedirectResponse constructor? That's the path you want to redirect to. It will need to be different to the current page, or you'll end up in a redirect loop
    – Clive
    Aug 17 at 15:25
  • This previous question should answer your question. Aug 17 at 19:24
  • @Clive yes, I mean the constructor. If it's the path I want to redirect to, then how is the function my_goto($path) called in a module? How to check if the old path of the current page requested == '/old_path', then new_path to redirect to = 'new_path'? I expect something like my_goto($current_path) {if($current_path == '/old_path'){$new_path = '/new_path'}}. Could you publish an example for a module as an answer? For I still don't understand it
    – stckvrw
    Aug 18 at 6:42

Browse other questions tagged or ask your own question.