开发者

PHP - Pass POST variables with header()?

I'm trying to use the header() function to create a redirect. I would like to display an error开发者_运维问答 message. Currently I'm sending the message as a parameter through the URL, however this makes it look quite ugly.

Is there a way to pass this value as a post variable instead?

Any advice appreciated.

Thanks.


Dan, You could start and store a session in PHP then save the message as a session variable. This saves you from having to transfer the message in an HTTP request.

Manipulating Sessions

//Start the session
session_start();

//Dump your POST variables
$_SESSION['POST'] = $_POST;

//Redirect the user to the next page
header("Location: bar.php");

Now, within bar.php you can access those POST variables by re-initiating the session.

//Start the session
session_start();

//Access your POST variables
$temp = $_SESSION['POST'];

//Unset the useless session variable
unset($_SESSION['POST']);

To read more about sessions, check out: http://php.net/manual/en/function.session-start.php


The header function is used to send HTTP response headers back to the user so actually you cannot use it to create request headers :(

One possibility is to use the CURL but I don't think it is worth of what you are doing.


Provided that you have local access to the page displaying the error, instead of redirecting you could include it in the page which caused the error and then programmatically display the error message.

if(something_went_wrong()) {
  require_once('errors.php');
  display_error('something really went wrong.');
  }

The errors.php file would then contain a definition for display_error($message), which displays the formatted message.


When passing variables between modules I have found it easier to construct an array from the variables, convert the array to json and store it in a db table with two columns, a varchar key and a text data. The json would go in data and the key could be anything you want. Then in the target module you just read that back, convert the json back to an array and voila, you have your variables. No $_POST, no $_SESSION, no fuss, no muss, quick and easy. Of course that assumes you have access to a database, although you could use a file on the server. $_POST is useless since it needs a and $_SESSION can be cranky and can lead to unexpected results. Otherwise you'd almost have to use ajax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜