drupalhttp-redirectdrupal-rules

Drupal rules php action


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?


Solution

  • 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.