You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP技术求助:如何从表单POST中保存会话变量并回显

Fixing Session Variable Storage from POST Form

Let's work through the issues in your code and get it working properly:

Key Issues in Your Original Code

  • Mismatched form input name and POST key: Your input has name="fColour", but you tried to access $_POST["favColour"] — these need to match exactly.
  • Inconsistent session variable keys: You stored $_SESSION["favColour"] but tried to echo $_SESSION["fColour"] later — the keys must be identical.
  • Incorrect check on the subsequent page: You used isset($_POST['Submit']) to check for the session variable, but after submitting the form, the subsequent page won't have POST data (unless you're submitting directly to it). Instead, you should check if the session variable itself exists.

Corrected Code for the Form/Submission Page

<?php
session_start();
// Only process data when the form is submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    // Use the exact name from the form input
    $favColour = $_POST["fColour"];
    // Store the value in session with a consistent key
    $_SESSION["favColour"] = $favColour;
    // Redirect to the display page to avoid duplicate submissions on refresh
    header("Location: display.php");
    exit;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <label for="fcolour">Favourite Colour: </label>
    <input type="text" name="fColour" id="fcolour">
    <input type="submit" name="submit" value="Submit">
</form>

Corrected Code for the Subsequent Display Page

<?php
session_start();
// Check if the session variable exists (not POST data)
if (isset($_SESSION["favColour"])) {
    echo "Your favourite colour is: " . $_SESSION["favColour"];
} else {
    echo "No favourite colour has been saved in your session yet.";
}
?>

What Changed?

  1. Unified naming: All references to the colour input (POST key, session key) now match to avoid typos.
  2. Safer submission handling: We check the request method and submit button existence to only process data when the form is actually submitted.
  3. Proper session check: The display page checks for the session variable directly, since POST data doesn't persist across page redirects.
  4. Redirect after submission: Using header("Location: ...") prevents users from accidentally resubmitting the form if they refresh the page.

内容的提问来源于stack exchange,提问作者Jarrod Austin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:40:19