Heim >Backend-Entwicklung >PHP-Tutorial >Ein möglicher Titel ist: Wie erstelle ich selbsteinreichende Formulare in PHP?
So erstellen Sie selbst einreichende Formulare in PHP
Beim Erstellen von Webformularen ist es oft notwendig, die Daten des Formulars an dieselben zurückzusenden Seite. Dies wird als Selbstveröffentlichungs- oder Selbsteinreichungsformular bezeichnet. Es gibt mehrere Methoden, um dies zu erreichen.
Methode 1: Verwendung von $_SERVER["PHP_SELF"]
Die empfohlene Methode ist die Verwendung von $_SERVER["PHP_SELF" ]-Variable, um das Aktionsattribut des Formulars anzugeben. Diese Variable enthält den Dateinamen des aktuellen Skripts:
<code class="php"><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <!-- Form controls --> <input type="submit" value="Submit"> </form></code>
Methode 2: Weglassen des Aktionsattributs
Ein alternativer Ansatz besteht darin, das Aktionsattribut vollständig wegzulassen. Standardmäßig senden die meisten Browser das Formular an die aktuelle Seite, wenn keine Aktion angegeben ist:
<code class="php"><form method="post"> <!-- Form controls --> <input type="submit" value="Submit"> </form></code>
Beispielformular
Das folgende Beispiel zeigt eine Selbstveröffentlichung Formular, das Namens- und E-Mail-Werte sammelt und auf derselben Seite anzeigt:
<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>
Das obige ist der detaillierte Inhalt vonEin möglicher Titel ist: Wie erstelle ich selbsteinreichende Formulare in PHP?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!