Friday, May 13, 2011

Redirection that works

Content administrators needed a way to control the URL to their external web application and be able to edit/show a maintenance message when the application was down for updates.

I created a new content type with a CCK link field for the URL and a single on/off check box for the administrator to turn the maintenance message on or off. The maintenance message lived in the default title and body.

I affected body output in the template for the new content type to send the user to the URL if the checkbox is not checked and show the maintenance message if it is checked.

My initial code looked like this:

<?php

//if the check box is not checked...
if($node->field_CHECKBOX[0]['value'] != 'on'){

//redirect the user to the URL
header('Location:'$node->field_URL[0]['url']);

}

//show the maintenance message if the user wasn't redirected.
print $node->content['body']['#value']; 

?>

My first problem was that if I created a node of this type and left the box unchecked for the redirection to occur, I couldn't edit the template. I added to the if statement that the URI couldn't start with '/admin' so it wouldn't redirect if I was on an admin page. At the same time, I decided to also make sure the node was published.

Here's what the code looked like after changes:

<?php

//if the check box is not checked, the URI doesn't start with '/admin' and the node is published...
if($node->field_CHECKBOX[0]['value'] != 'on'  && substr($_SERVER["REQUEST_URI"], 0, 6) != '/admin' && $node->status == 1){

//redirect the user to the URL
header('Location:'$node->field_URL[0]['url']);

}

//show the maintenance message if the user wasn't redirected.
print $node->content['body']['#value']; 

?>

This code worked fine while I was logged in, but when I tested as an anonymous user, it worked on the first click and stopped redirecting afterwards. Flushing the cache or refreshing the page didn't fix the problem.

Through some testing, I discovered that it was the header() function that was the problem. I think it worked inconsistently because that function is suppose to be used on the first line of a page.

In searching for a different way to redirect in Drupal, I found the function drupal_goto(). This worked every time the page was accessed.

Here is the final code:

<?php

//if the check box is not checked, the URI doesn't start with '/admin' and the node is published...
if($node->field_CHECKBOX[0]['value'] != 'on' && substr($_SERVER["REQUEST_URI"], 0, 6) != '/admin' && $node->status == 1){

//redirect the user to the URL using HTTP response code 307
drupal_goto($path = $node->field_URL[0]['url'], $query = NULL, $fragment = NULL, $http_response_code = 307);

}

//show the maintenance message if the user wasn't redirected.
print $node->content['body']['#value']; 

?>

In conclusion, drupal_goto() works best for redirecting within the content of a node.

No comments:

Post a Comment