2

I am experimenting with the Rules module for the first time and I am attempting to redirect my users with some simple php code as below:

drupal_set_message('testing');
drupal_goto('node/3');

The first line of code executes but the second, which should direct my users to node/3, does not have the desired effect.

How can I get this redirecting feature working?

halfer
  • 19,824
  • 17
  • 99
  • 186
sisko
  • 9,604
  • 20
  • 67
  • 139

1 Answers1

3

It's most likely because you have ?destination=some/path in the page URL, these lines in drupal_goto() cause any path you pass to the function to be overwritten by whatever's in the URL:

if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
  $destination = drupal_parse_url($_GET['destination']);
  $path = $destination['path'];
  // ...

You can probably get around it simply by changing your code to this:

if (isset($_GET['destination'])) {
  unset($_GET['destination']);
}
drupal_goto('node/3');

If that doesn't work try adding this line before drupal_goto:

drupal_static_reset('drupal_get_destination');

which will reset the static cache for the drupal_get_destination() function, which also gets involved in this process at some point (I think).

If all else fails, go old school:

$path = 'node/3';
$options = array('absolute' => TRUE);
$url = url($path, $options);
$http_response_code = 302;
header('Location: ' . $url, TRUE, $http_response_code);
drupal_exit($url);

That's pretty much nicked straight from the drupal_goto() function itself and will definitely work.

Clive
  • 36,918
  • 8
  • 87
  • 113
  • Thanks for the rich selection of suggestions. Of them all it was the last one, lifted from the goto function, that worked. Can you possibly give some indication of how you dissect and understand drupal so thoroughly? – sisko Dec 13 '11 at 22:20
  • There's no easy answer to that I'm afraid, I've had to bend Drupal to do things it wasn't necessarily meant to do so often that I've had to dig into the core files and see what's happening hundreds of times; it's almost second nature now to know where the source of a problem will probably be. I also followed the development of Drupal 7 pretty closely which helped my understanding of the system a lot. The best advice I can give is don't be afraid to get stuck in to the core files and just keep following the trail of functions until you find what's causing the problem :) – Clive Dec 14 '11 at 18:40