Self-Posting PHP Forms: How to Submit Results to the Same Form
Forms that submit results to themselves, rather than an external location, are known as self-posting forms. This article explores the best practices for creating self-posting forms in PHP.
Proper Approach: Using $_SERVER["PHP_SELF"]
To create a self-posting form, you can utilize the $_SERVER["PHP_SELF"] variable in conjunction with htmlspecialchars to prevent security vulnerabilities. This method ensures W3C compliance and is compatible with most browsers.
Example Form
Here's an example form that takes a name and email, then displays the submitted values:
<code class="php"><?php if (!empty($_POST)): ?> Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br> Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br> <?php else: ?> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> Name: <input type="text" name="name"><br> Email: <input type="text" name="email"><br> <input type="submit"> </form> <?php endif; ?></code>
Empty Action Attribute
You can also omit the action attribute of the form tag. While this is not W3C valid, it works in most modern browsers. In this case, the form will automatically submit to itself. However, note that this approach is not compliant with W3C standards.
The above is the detailed content of How to Create Secure Self-Posting PHP Forms: Best Practices and Examples?. For more information, please follow other related articles on the PHP Chinese website!