HTML POST 到多个 .php 文件

HTML POST to multiple .php files

这是我现在的表格。


## on index.php
        <form action="index2.php" method="POST">
            <select name="profile">
                <option value="basic" selected>Easy</option>
                <option value="intermediate">Medium</option>
                <option value="advanced">Hard</option>
            </select>
            <br>
                <input type="submit"/>
        </form>

在index2.php,我可以成功地做$_POST['profile']。但是,我想 $_POST['profile'] 我有另一个 .php 文件,它叫做 test.php.

当我尝试在 test.php 上执行 $_POST['profile'] 并将其分配给变量 $test 时,返回错误。

Notice: Undefined index: profile in C:\xampp\htdocs\testfolder\test.php on line 15

导致错误的代码:

$test = $_POST['profile'];

## this is on test.php

预期结果:成功 POST“个人资料”。

我该怎么做?

您可以在 POST 之后将该变量存储到会话变量中,并且您可以从每个页面的代码中的任何位置访问该变量。

你的表格:

<form action="index2.php" method="POST">
    <select name="profile">
        <option value="basic" selected>Easy</option>
        <option value="intermediate">Medium</option>
        <option value="advanced">Hard</option>
    </select>
    <br>
        <input type="submit"/>
</form>

在第 index2.php 页上,您必须使用此方法捕获 POST 数据 index2.php

<?php 

session_start(); // starting the session

if(isset($_POST)){
      $_SESSION['profile'] = $_POST['profile'] // sets the $_POST['profile'] value to $_SESSION['profile'] 
}
?>

现在 $_SESSION 将成为您的全局变量,您可以随时访问它,任何页面只需添加 session_start();在每一页上。

test.php:

<?php 
session_start(); //starting the session
echo $_SESSION['profile'];
?>

它将 return 您在任何页面上的期望值。请在此处阅读 $_SESSION