Home > Backend Development > PHP Tutorial > How to Create Self-Submitting Forms in PHP?

How to Create Self-Submitting Forms in PHP?

Mary-Kate Olsen
Release: 2024-10-29 03:26:30
Original
556 people have browsed it

How to Create Self-Submitting Forms in PHP?

Creating Self-Submitting PHP Forms

In web development, it may be necessary to create forms that submit data to themselves. This type of form is known as a self-posting or self-submitting form.

Solution

There are two primary methods to create self-submitting forms in PHP:

1. Using $_SERVER["PHP_SELF"]

This approach is recommended for both security and accessibility reasons. Here's how it's done:

<code class="php"><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    ... (form fields) ...
    <input type="submit" value="Submit">
</form></code>
Copy after login

In this code, htmlspecialchars() is used to prevent potential exploits.

2. Omitting the Action Attribute

While not W3C compliant, omitting the action attribute can also achieve self-submission. Browsers typically default to submitting the form to itself if the action attribute is empty.

<code class="php"><form method="post">
    ... (form fields) ...
    <input type="submit" value="Submit">
</form></code>
Copy after login

Example

Here's an example of a self-submitting form that collects a user's name and email:

<code class="php"><?php
if (!empty($_POST)) {
    echo "Welcome, " . htmlspecialchars($_POST["name"]) . "!<br>";
    echo "Your email is " . htmlspecialchars($_POST["email"]) . ".<br>";
} 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" value="Submit">
    </form>
    <?php
}
?></code>
Copy after login

The above is the detailed content of How to 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