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;
}

/**
 * Set a session message
 *
 * @param string $message Message to set
 *
 * @return string - Message ID which is the $_SESSION index that holds the message
 */
function set_session_message($message) {
	$message_id = sha1(microtime(true));
	$_SESSION[$message_id] = $message;

	return $message_id;
}

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.

About Aaron D. Campbell

Owner and lead developer at BlueDog, Aaron has 10+ years of web development experience, it a regular core contributor to the WordPress project, and has released many WordPress plugins.
This entry was posted in PHP and tagged , . Bookmark the permalink.

14 thoughts on “PHP function to Redirect a user with a message

  1. Jem says:

    What, no mention of the security risks behind echoing unsanitised $_GET contents back to the browser? Tut tut :p

  2. I’m never echoing $_GET data to the browser. I use a $_GET variable as a key to access and echo a value stored in the session, and I redirect to the current page (using all the current $_GET variables), but I don’t echo them to the browser.

  3. Jem says:

    I replied to your email with the correction to my above comment; I can only blame a long day and a lack of coffee for my typing $_GET instead of $_SESSION! 0:)

  4. $_SESSION isn’t really “unsanitary” …it only contains what you put in it. Think of all your variables (specifically all the superglobals in this case) as lockers that you store stuff in. $_GET, $_POST, $_REQUEST, and $_COOKIE have no lock on them, so anyone (your users) can put stuff in them. They are UNSAFE, and should be sanitized thoroughly. $_SERVER is a two part locker, the top has no lock, and the bottom does. Things like PHP_SELF can contain undesired user input (read XSS Woes over at PeeaycHPee). Those also need to be sanitized. However, the $_SESSION locker has a lock, and only contains what you put in there. If you dump stuff from another area in there without looking at it, it COULD contain dangerous data. However, if you simply don’t put bad data in, you won’t get bad data out.

  5. Having said all that, when in doubt…SANITIZE!

  6. Jem says:

    I hope you didn’t type all that out for my benefit :p

    “However, if you simply don’t put bad data in, you won’t get bad data out.” – obviously only an idiot do that, but that doesn’t cover the risks of sessions on badly configured shared hosting coupled with possibility of session poisoning (I only realised it had it’s own term last night, hehe): http://en.wikipedia.org/wiki/Session_poisoning

    A shared host user manipulates the session and then calls it using using $_GET? Sounds perfectly feasible to me.

    Call me paranoid but I would say ALWAYS sanitise, rather than simply “when in doubt”. Better safe than sorry, no?

  7. Session poisoning (also referred to as “Session data pollution” and “Session modification”) is to exploit insufficient input validation in server applications which copies user input into session variables.

    I’m often guilty of forgetting some of the things that can cause these kinds of problems. Chalk it up to being spoiled. I work with custom written software (mine) on dedicated Rackspace servers. However, there are a few ways that you can cause session poisoning.

    First, you can insufficiently validate content that you store in it. To fix this, simply be careful about what you put in it, making sure it is what you mean to put there. Don’t assume a user put a number into the “total cost” field. Assume your users are malicious.

    Secondly, you could have scripts or applications that use overlapping session variables. I see this as a worse possibility because “joe no coder” could download and install two conflicting scripts without even knowing it. To solve this, check out the applications you are using. If you can’t understand the code, at LEAST do some serious research.

    Lastly, you could have a poorly configured shared server. Again, this is dangerous because people often don’t have control over this. Again, however, research is your friend. Please like Web Hosting Talk often have hundreds of reviews on hosts.

    Jem: this isn’t aimed at you. This is aimed at filling in the gaps in the article above, for the users that need it.

  8. OpenBSD says:

    Hi,
    can you send full php code with tag ? i dont care this : $my_get[] = "{$n}={$v}";

    thanks .
    Best regards.

  9. shabzo says:

    when a user wants to change his password and is successfull i have this
    $msg[] = “Your new password is updated”;
    //header(“Location: mysettings.php?msg=Your new password is updated”);
    } else
    {
    $err[] = “Your old password is invalid”;
    //header(“Location: mysettings.php?msg=Your old password is invalid”);
    }
    i want to display the message and then redirect to the login page

    • Instead of displaying the message and THEN redirecting, just use the code from this post and display the message on the page you’re redirecting to.

      if ( /* Successfully changed pass */ ) {
          redirect( "Your new password is updated", "/page/where/success/goes.php" );
      } else {
          redirect( "Your old password is invalid", "/page/to/try/again.php" );
      }
      

      Then of course you need the code from above to display the messages on both “/page/where/success/goes.php” and “/page/to/try/again.php”:

      if (isset($_GET['message']) && isset($_SESSION[$_GET['message']])) {
      	echo $_SESSION[$_GET['message']];
      	unset($_SESSION[$_GET['message']]);
      }
      

Leave a Reply

Your email address will not be published. Required fields are marked *

Note: If you are replying to another commenter, click the "Reply to {NAME} ↵" button under their comment!