2

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.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
  • 1
    http://www.php.net/manual/en/book.session.php – user1909426 Mar 10 '13 at 01:38
  • While not a duplicate, this question is similar to this http://stackoverflow.com/questions/653090/how-do-you-post-to-a-page-using-the-php-header-function which is worth a read because it has a relevant info regrading the OP's intent. – Mark Fox Mar 10 '13 at 01:53

1 Answers1

3

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

error.php

// 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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • ty but for some reason the session does not seem to get to the next site, i must have an error in my code somwhere, i cannot set the session_start(); at the error div, header sendt, so i tried setting it at the top, with a echo @_SESSION['error']; die(); but its empty, it works fine on the insert function, when i echo it. – Dsadsadsa Sdasdasda Mar 10 '13 at 01:57
  • @DsadsadsaSdasdasda `session_start()` should be called at the top, and must be called in _both_ files. Is `error.php` on a different domain, or the same domain? If it is on the same domain, this should work correctly. – Michael Berkowski Mar 10 '13 at 02:02