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 yourisset($_POST['submit'])check never triggers. - Submit button has no
nameattribute: The submit input doesn't havename="submit", so even if you used POST, this variable wouldn't exist in the$_POSTarray. - Syntax error in
actionattribute: 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?
- Added
method="POST"to the form: This ensures data is sent via the POST method, matching your$_POSTchecks. - Added
name="submit"to the submit button: Now$_POST['submit']will exist when the form is submitted. - Fixed the
actionattribute:- 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!)
- 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
相关产品推荐
相关产品推荐

