2

我有一个名为 insert_comment.php 的表单,它包含以下功能:

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

在代码的下方,$error_message 被发送到函数 die,然后函数 die 将用户重定向到 mydomain.com/post/error.php,我从 URL 获得错误消息:

$error = $_GET["error"];

echo 'some text '. $error .' sometext';

有没有办法使用 POST 重定向来做同样的事情?我不喜欢在 URL 中显示整个错误消息,它看起来很丑陋。

4

1 回答 1

3

虽然使用 POST 可能会很复杂,但这是错误的策略,而不是 POST 请求的目的。

正确的策略是将此信息放入 session中,并从那里显示它,然后在显示时删除 session 密钥。

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

错误.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']);
}

完全相同的策略可用于在重定向后向用户显示其他消息,例如操作成功。根据需要在数组中使用尽可能多的不同键$_SESSION,并在向用户显示消息时取消设置它们。

于 2013-03-10T01:40:12.410 回答