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

PHP表单回显与GET/POST数据处理异常:$_SERVER['PHP_SELF']及POST判断失效

Fixing Your PHP Form Submission Issues

Let's break down the problems with your code and get it working properly:

Key Issues Identified

  • Form uses default GET method: Your form doesn't specify method="POST", so all data is sent via GET instead of POST. That's why your isset($_POST['submit']) check never triggers.
  • Submit button has no name attribute: The submit input doesn't have name="submit", so even if you used POST, this variable wouldn't exist in the $_POST array.
  • Syntax error in action attribute: When echoing $_SERVER['PHP_SELF'], you need to properly quote the attribute value and handle the variable correctly within your echoed HTML string.

Fixed Code Example

<?php
echo "<html><body>";

// Check if form was submitted via POST
if(isset($_POST['submit'])) {
    $name = $_POST['firstname'];
    echo "User Has submitted the form and entered this name : <b> $name </b>";
}

// Output the form with corrected attributes
echo '
<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="POST">
    First name:<br>
    <input type="text" name="firstname" value="John"><br>
    Last name:<br>
    <input type="text" name="lastname" value="Rambo"><br><br>
    <input type="submit" name="submit" value="Submit">
</form>
</body></html>';
?>

What Changed?

  1. Added method="POST" to the form: This ensures data is sent via the POST method, matching your $_POST checks.
  2. Added name="submit" to the submit button: Now $_POST['submit'] will exist when the form is submitted.
  3. Fixed the action attribute:
    • Used single quotes for the echoed HTML block to avoid variable interpolation issues
    • Wrapped $_SERVER['PHP_SELF'] in double quotes for the HTML attribute
    • Added htmlspecialchars() to prevent XSS vulnerabilities (always sanitize user-facing output!)
  4. Formatted the echoed HTML for readability (not strictly necessary, but makes maintenance easier)

Bonus Note

Using $_SERVER['PHP_SELF'] is fine here, but make sure to always sanitize it with htmlspecialchars() to prevent cross-site scripting attacks. Alternatively, you can leave the action attribute empty (action="") which will submit to the same page by default.

内容的提问来源于stack exchange,提问作者Satyam Veer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:04:09