I have a form called insert_comment.php it contains this function:
function died($error) { // if something is incorect, send to given url with error msg
header("Location: http://mydomain.com/post/error.php?error=" . urlencode($error));
die();
}
Further down the code, the $error_message is sent to function die, then function die redirects the user to mydomain.com/post/error.php where I get the error message from the URL:
$error = $_GET["error"];
echo 'some text '. $error .' sometext';
Is there any way to do the exact same thing using a POST redirect? I don't like displaying the entire error message in the URL, it looks very ugly.
While it is possible though complicated to do it with a POST, that is the wrong strategy, and not the purpose of a POST request.
The right strategy is to place this information into the session, and display it from there, then remove the session key when it has been shown.
// session_start() must have been called already, before any output:
// Best to do this at the very top of your script
session_start();
function died($error) {
// Place the error into the session
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
// Read the error from the session, and then unset it
session_start();
if (isset($_SESSION['error'])) {
echo "some text {$_SESSION['error']} sometext";
// Remove the error so it doesn't display again.
unset($_SESSION['error']);
}
The exact same strategy can be used to display other messages like action successes back to the user after a redirect. Use as many different keys in the $_SESSION
array as you need, and unset them when the message has been shown to the user.