July 9th, 2007 PHP function to Redirect a user with a message

One of the common things that you need to do in PHP is redirect a user, and display a message on whatever page you are sending them to. There are a lot of reasons for this, but the most common is to avoid a user refresh from resubmitting a form. Instead, process the form data, and redirect the user (even if you redirect them to the same page). Here is a function I use for this very purpose. It requires that you are using sessions. It stores the message in the session, and passes a has in the URL. This way, you can use any length message you want, and display it only once.

First, the function:

/**
* This function redirects to a specified page (current page by default), but
* passes along a message in the users SESSION.  It passes a GET var that tells
* where that message is.  Used properly, this will avoid giving the user a
* duplicate message on page refresh.
*
* @param string $message - Message to pass along via session
* @param string[optional] $page - page to redirect to (with leading /)
*/
function redirect($message, $page=FALSE) {
$my_get = array();
$_GET['message'] = set_session_message($message);
foreach ($_GET as $n=>$v) {
$my_get[] = "{$n}={$v}";
}
if (count($my_get) > 0) {
$my_get = '?'.implode('&',$my_get);
} else {
$my_get = '';
}

if (is_string($page)) {
$location = $page;
} else {
$location = $_SERVER['SCRIPT_NAME'];
}

$http = (!isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS'])!=’on’)?’http’:'https’;

header(”Location: {$http}://{$_SERVER['HTTP_HOST']}{$location}{$my_get}”);
exit;
}

Use it like this:

 
//To redirect to the current page
redirect('Place your message here');
//To go to another page
redirect('Place your message here', '/next_page.php');
 

Now, you will want to display the message. I use this code in my template file
 
if (isset($_GET['message']) && isset($_SESSION[$_GET['message']])) {
echo " 

{$_SESSION[$_GET['message']]}

“;
unset($_SESSION[$_GET['message']]);
}

In this way, the message is displayed, but then unset so it’s not displayed again on refresh.

Simple and effective.

7 Responses to “PHP function to Redirect a user with a message”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Search