Creating a Self-Posting PHP Form
This article delves into the methods for creating a self-submitting form in PHP, a common requirement for various web applications.
The Mechanics of a Self-Posting Form
Unlike traditional forms that submit data to a different page, a self-posting form submits the data to itself. This functionality enables the form to update dynamically without reloading a separate page.
Using $_SERVER["PHP_SELF"]
The proper approach to create a self-posting form is to use the $_SERVER["PHP_SELF"] variable. This variable provides the current script's path and is often used in conjunction with htmlspecialchars to prevent potential exploits.
Omitting the Action Attribute
An alternative method is to omit the action= part in the form's opening tag. While not W3C valid, this practice is widely supported by browsers. When the action is empty, most browsers will default to submitting the form to the current page.
An Example Form
Consider the following example that takes a name and email as input:
<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>
This form displays the submitted values on the same page after the user clicks the submit button.
The above is the detailed content of How Do I Create a Self-Posting Form in PHP?. For more information, please follow other related articles on the PHP Chinese website!