How to Create Self-Submitting Forms in PHP
When creating web forms, it's often necessary to submit the form's data back to the same page. This is called a self-posting or self-submitting form. There are several methods to achieve this.
Method 1: Using $_SERVER["PHP_SELF"]
The recommended method is to use the $_SERVER["PHP_SELF"] variable to specify the action attribute of the form. This variable contains the current script's filename:
<code class="php"><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <!-- Form controls --> <input type="submit" value="Submit"> </form></code>
Method 2: Omitting the Action Attribute
An alternative approach is to omit the action attribute altogether. By default, most browsers will submit the form to the current page if no action is specified:
<code class="php"><form method="post"> <!-- Form controls --> <input type="submit" value="Submit"> </form></code>
Example Form
The following example demonstrates a self-posting form that collects name and email values and displays them on the same page:
<code class="php"><?php // Check if the form has been submitted if (!empty($_POST)) { // Get the form values $name = htmlspecialchars($_POST["name"]); $email = htmlspecialchars($_POST["email"]); // Display the submitted values echo "Welcome, $name!<br>"; echo "Your email is $email.<br>"; } else { // Display the form ?> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <br> <label for="email">Email:</label> <input type="text" id="email" name="email"> <br> <input type="submit" value="Submit"> </form> <?php } ?></code>
The above is the detailed content of A possible title is: How do I create self-submitting forms in PHP?. For more information, please follow other related articles on the PHP Chinese website!