Consider the following code:
<?php // file1.php
if(isset($_POST['submit'])) {
echo "You can see this important message but the header() won't work.";
header('Location: somewhere_else.php');
}
?>
<form action='' method='post'><input type='submit'></form>
Ok, let’s try to buffer our output to solve the problem.
<?php // file2.php
ob_start();
if(isset($_POST['submit'])) {
echo "header() will work but you won't see this important message.";
header('Location: somewhere_else.php');
}
?>
<form action='' method='post'><input type='submit'></form>
<?php
ob_get_flush();
?>
These greatly simplified examples shows a common problem that happens with posting, forms, and header redirection: What do you do if you need (or accidentally) print some text before the redirect? The answer is: Sessions.
<?php // session_messages.php
start_session();
// add_message() - queues a message for display later
// msg - the contents of the message
// type - the type of message
function add_message($msg,$type='notice') {
if(!isset($_SESSION['messages'])) {
$_SESSION['messages']=array();
}
$_SESSION['messages'][]=array('type'=>$type,'msg'=>$msg);
}
function add_notice($msg) {
add_message($msg,'notice');
}
function add_error($msg) {
add_message($msg,'error');
}
function add_warning($msg) {
add_message($msg,'warning');
}
function debug_item($a) {
add_message('<pre>'.print_r($a).'</pre>','debug');
}
// display_messages() - show the queued messages
function display_messages() {
if(count($_SESSION['messages'])) {
echo "<div class='messages'>";
foreach($_SESSION['messages'] as $v) {
echo "<div class='".$v['type'].">".$v['msg']."</div>\n";
}
$_SESSION['messages']=array();
echo "</div>";
}
}
?>
Now imagine what happens when all your error messages pass through add_error. The file1.php example would become
<?php // file3.php
require_once "session_messages.php";
if(isset($_POST['submit'])) {
add_notice("You can see this message no matter what happens*");
add_warning("* as long as somewhere_else.php calls display_messages().");
header('Location: somewhere_else.php');
}
// you can also display them on the same page if you don't redirect.
display_messages();
?>
<form action='' method='post'><input type='submit'></form>
From here the sky is the limit – you could sort messages by type, you could hide errors so that only the administrators can see them. Debugging becomes easier, too.
Share on Facebook