Home > Backend Development > PHP Tutorial > A possible title is: How do I create self-submitting forms in PHP?

A possible title is: How do I create self-submitting forms in PHP?

Barbara Streisand
Release: 2024-10-30 08:57:27
Original
473 people have browsed it

A possible title is: How do I create self-submitting forms in PHP?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template