简单的 PHP 重定向后获取代码示例

php
2022-08-30 10:20:41

我发现许多描述PRG的网站,但没有简单的PHP代码示例。


以下是我实现的内容:

  1. 具有操作:。form.phpvalidate.php
  2. 用户从未见过;如果验证所有,如果有效将其写入数据库并生成确认页面的HTML /如果无效,它将生成错误页面的HTML,解释错误的内容。validate.php$_GET
  3. 生成的任何 HTML 都存储在变量中,然后调用 。$_SESSIONvalidate.phpheader('Location: <as appropriate>);
  4. 的(如果用户读取 URL)仅由 组成。submitted.phpinvalid_input.phpecho $_SESSION['form_html'];

在我看来,这就像防止页面重新加载和后退按钮问题一样。

我是否试图通过重新发明轮子来搞砸?


答案 1

最简单的场景:

if ($_POST) {
   // Execute code (such as database updates) here.

   // Redirect to this page.
   header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
   exit();
}

用。不要使用,因为在大多数CMS系统和框架中会引用。REQUEST_URIPHP_SELFPHP_SELF/index.php


答案 2

一段代码:

if (count($_POST)) {
    // process the POST data
    // your code here- so for example to log a user in, register a new account..
    // ...make a payment...etc

    // redirect to the same page without the POST data, including any GET info you
    // want, you could add a clause to detect whether processing the post data has 
    // been successful or not, depending on your needs

    $get_info = "?status=success";

    // if not using rewrite
    // header("Location: ".$_SERVER['PHP_SELF'].$get_info);

    // if using apache rewrite
    header("Location: ".$_SERVER['REQUEST_URI'].$get_info);
    exit();
}

推荐