在此特定方案中,如何使用POST而不是GET [英] How do I use POST rather then GET in this specific scenario

查看:105
本文介绍了在此特定方案中,如何使用POST而不是GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为insert_comment.php的表单它包含这个函数:

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

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

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';

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

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.

推荐答案

虽然有可能虽然很复杂用POST来做,这是错误的策略,而不是POST请求的目的。

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



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

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

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.

这篇关于在此特定方案中,如何使用POST而不是GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆