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

PHP简易表单空提交提示失效:为何部分PHP代码无法正常运行?

Fixing Your PHP Form's Empty Submission Error

Hey there! Let's sort out that missing error message for empty submissions. The problem is likely that you're not explicitly checking if the submitted content is actually empty before showing the success message. Here's how to fix it step by step:

Key Issues to Address

  • You probably only check if the form was submitted (via POST) but skip verifying if the input has actual content.
  • Don't forget to handle whitespace-only inputs—users might accidentally submit spaces, which should count as empty too.

Complete Working Code

<?php
// Start with an empty message variable
$display_message = "";

// Check if the form was submitted via POST
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Grab the input value and strip extra whitespace from start/end
    $user_input = trim($_POST["message"]);
    
    // First check if the input is empty (including whitespace-only)
    if (empty($user_input)) {
        $display_message = "Error: You didn't write anything";
    } else {
        // If we get here, the input is valid—you could add submission logic here (like sending an email)
        $display_message = "Your message has been sent";
    }
} else {
    // Page loaded for the first time, no submission yet
    $display_message = "You have not written anything yet.";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Simple PHP Form</title>
</head>
<body>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <label for="message">Your Message:</label><br>
        <textarea id="message" name="message" rows="3" cols="40"></textarea><br>
        <button type="submit">Send Message</button>
    </form>
    <p><?php echo $display_message; ?></p>
</body>
</html>

What Changed & Why

  1. Whitespace Handling: Using trim() ensures that inputs with only spaces/tabs/newlines are treated as empty—this covers edge cases users might trigger accidentally.
  2. Empty Check First: Inside the POST request check, we first verify if the input is empty. Only if it's not empty do we show the success message.
  3. XSS Protection: htmlspecialchars($_SERVER["PHP_SELF"]) prevents cross-site scripting attacks, which is a good practice even for simple forms.

This should now handle all three of your required cases perfectly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:16:18