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

kmpatx3s  于 2023-01-24  发布在  PHP
关注(0)|答案(6)|浏览(124)

我发现很多网站描述PRG,但没有简单的PHP代码示例。
下面是我实现的:

  1. form.php有一个操作:validate.php.
    1.用户从未看到validate.php;if验证所有$_GET,如果有效,则将其写入数据库并生成确认页面的HTML/如果无效,则生成错误页面的HTML,解释错误。
    1.生成的HTML存储在$_SESSION变量中,然后validate.php调用header('Location: <as appropriate>);
  2. invalid_input.phpsubmitted.php(在用户读取URL的情况下)仅由echo $_SESSION['form_html'];组成。
    在我看来,这似乎是对页面重载和后退按钮问题的保护。
    我是不是因为试图重新发明轮子而搞砸了?
z6psavjg

z6psavjg1#

最简单的场景:

<?php
if ($_POST) {
    //validate the input

   if (/* input is OK */) {
       // Execute code (such as database updates) here.
       // Redirect to this page.
       header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
       exit();
    }
}
?>
<html>
<!-- here goes your HTML page with a form -->

使用REQUEST_URI。不要使用PHP_SELF,因为在大多数CMS系统和框架中,PHP_SELF指的是/index.php

4szc88ey

4szc88ey2#

代码片段:

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

zi8p0yeb3#

Browser
   HTML form
  method=POST
       |
       v
    PHP app
  reads $_POST
sends 303 header
       |
       v
    Browser
receives header
 redirected to
   new page
       |
       v
    PHP app
  reads $_GET
 does whatever

一个常见的用法是登录验证。这是用户提交登录表单时的流程。PHP应用程序通过$_POST变量验证用户。当用户成功验证时,将303标头发送回浏览器。因此用户被重定向到一个新页面。

68bkxrlz

68bkxrlz4#

我想向您介绍一种方法,它在框架中的使用范围更广,使用的细节也更多。

我们要做的

我们有一个名为index.php的文件。

  • 我们要提交一份表格
  • 我们将检查此提交
  • 我们将POST数据添加到会话中
  • 我们将用户重定向到确认页面
  • 我们将显示数据并让用户确认。
  • 我们将提交,并最终处理数据。
  • 我们将重定向回index.php并显示通知。

代码

<?php
if (!isset($_SESSION)) session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    switch ($_POST['submit']) {
        case 'add':
            // This is where our first POST will end up
            // We can perform actions such as checking the data here

            // After that we will add the POST data to a session
            $_SESSION['postdata'] = $_POST;
            // and unset the $_POST afterwards, to prevent refreshes from resubmitting.
            unset($_POST);

            // Now we will redirect...
            header("Location: ".$_SERVER['PHP_SELF']);
            break;
        case 'confirm':
            // We can now insert the data into the database or email it

            // Then we will unset the session and redirect back
            unset($_SESSION['postdata']);

            // This is to display our notification
            $_SESSION['success'] = true;

            // And there we go again...
            header("Location: ".$_SERVER['PHP_SELF']);
            break;
    }
    // We will exit here because we don't want the script to execute any further.
    exit;
}
?>

<?php if (isset($_SESSION['success']) && $_SESSION['success'] == true): ?>
    <p>Our data has been processed succesfully</p>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['postdata'])): ?>
    <p>
        You want to add the following data:<br />
        <pre><?php print_r($_SESSION['postdata']); ?></pre>
        Is this correct?<br />
        <form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
            <button type="submit" name="submit" value="confirm">Yes</button>
        </form>
    </p>
<?php else: ?>
    <p>
        <form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
            <input type="text" name="..."><br />
            <input type="text" name="..."><br />
            <input type="text" name="..."><br />
            <input type="text" name="..."><br />
            <button type="submit" name="submit" value="add">Add something</button>
        </form>
    </p>
<?php endif; ?>
mwyxok5s

mwyxok5s5#

这里是form.php

<?php
session_start();
// 1) _____________________________________________ POST _____________________________
if ( count($_POST) ) {
    $ermsg ='';
    …
    check data, write some data to database(s), set error message(s) if any
    …
    $userdata1 = $_POST['htUserdata1'];
    $userdata2 = $_POST['htUserdata2'];
    …

    $_SESSION['PRG'] = array('field1'=>$userdata1,'field2'=>$userdata1,…,'ermsg'=>$ermsg);
    session_write_close();
    header('Location: ' . $_SERVER['REQUEST_URI'].'?z',true,303);
    exit;
// 2) _____________________________________________ REDIRECT ________________________
} else if ( array_key_exists('PRG',$_SESSION) ) {
    $userdata1 = $_SESSION['PRG']['field1'];
    $userdata2 = $_SESSION['PRG']['field2'];
    …
    $ermsg = $_SESSION['PRG']['ermsg'];
    unset($_SESSION['PRG']);
// 3) _____________________________________________ GET ______________________________
} else {
    …
    retrieve data from database(s)
    …
    $userdata1 = dbGet1();
    $userdata2 = dbGet2();
    …
    $ermsg = '';
}
// 4) _____________________________________________ DISPLAY _________________________
?>
<!DOCTYPE html>
<html lang="fr">
    …
<form method="post" action="form.php" accept-charset="utf-8">
        <input id="htUserdata1" name="htUserdata1" type="text"/>
        <input id="htUserdata2" name="htUserdata2" type="text"/>
        …
</form>
<script language="javascript">
"use strict";
<?php
$G['htUserdata1'] = $userdata1;
$G['htUserdata2'] = $userdata2;
    …
$G['ermsg'] = $ermsg;
$myJSON = json_encode($G);
echo "var G=$myJSON;";
?>
document.getElementById('htUserdata1').value = G.htUserdata1;
document.getElementById('htUserdata2').value = G.htUserdata2;
    …
if ( G.ermsg !=='')    alert(G.ermsg);
</script></body></html>
6mw9ycah

6mw9ycah6#

来电者.htm

<form method="post" action="Callee.php?Query1">
    <input type="text"   name="PostData" />
    <input type="submit" value="Go"      />
</form>

Callee.php(被调用两次。)

if ($_POST) {
    header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); 
    // PART1: Use $_POST and $_GET to execute database updates here...

    // Now any display (i.e. echo or print) will come after the header.
    // ...

   die;  // When done, GET 'myself' to execute PART2 below.
}

// PART2: Results page goes here...
echo 'PART 2 display output: '; var_dump($_GET);

请注意,其中涉及两个查询字符串

看看var_dump对$_GET是怎么说的:

PART 2 display output: array(1) { ["Query1Query2"]=> string(0) "" }

将标题 * 放在POST部分的末尾 * 时出现问题,如下所示:

header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); die;

php手册上说:“请记住,在发送任何实际输出之前,必须调用header(),无论是通过普通HTML标记、文件中的空行还是从PHP。使用include、require函数或其他文件访问函数读取代码,并在调用header()之前输出空格或空行,这是一个非常常见的错误。使用单个PHP/HTML文件时也存在同样的问题。”
但是如果你需要根据POST部分的情况来构建Query 2,那么它可能需要放在POST部分的底部,这是可以的,只要你不试图在它上面插入任何echo,即使是测试也不行。

相关问题