Home >Backend Development >PHP Tutorial >How to build a form using PHP?

How to build a form using PHP?

PHPz
PHPzOriginal
2024-04-20 17:36:01610browse

How to build a form in PHP? Create a form using the ff9c23ada1bcecdd1a0fb5d5a0f18437 tag, specifying the action and method attributes. Collect user input, including text, email, radio buttons, and checkboxes, through the d5fd7aea971a85678ba271703566ebfd element. Use the $_POST or $_GET array to collect submitted data. Write server-side scripts to process form data, such as validating, storing, or sending emails.

如何使用 PHP 构建表单?

How to build a form in PHP

Forms are an indispensable component in web development and are used to collect user input. This article will take you through how to build a form in PHP and provide practical examples for your reference.

Syntax for building a form

To create a form, you need to use the ff9c23ada1bcecdd1a0fb5d5a0f18437 tag. The ff9c23ada1bcecdd1a0fb5d5a0f18437 tag has the following attributes:

  • action: Specifies the script file to process the form data after submitting the form.
  • method: Specify the HTTP method to submit data to the server. Common methods are GET and POST.

The following is a simple PHP form syntax:

<form action="submit.php" method="post">
  <input type="text" name="name" placeholder="请输入您的姓名">
  <input type="email" name="email" placeholder="请输入您的邮箱地址">
  <input type="submit" value="提交">
</form>

Collect and process form data

When the user submits the form, the data will Submit to server-side script via the $_POST array (for the POST method) or the $_GET array (for the GET method).

The following is a sample code for processing form data:

$name = $_POST['name'];
$email = $_POST['email'];

// 验证表单数据或将其存储到数据库中,具体取决于你的需求

Practical case: Contact form

Let us build a simple contact form as a practical case .

HTML code:

<form action="submit.php" method="post">
  <label for="name">姓名:</label>
  <input type="text" name="name" id="name">
  <br>
  <label for="email">邮箱地址:</label>
  <input type="email" name="email" id="email">
  <br>
  <label for="message">留言:</label>
  <textarea name="message" id="message"></textarea>
  <br>
  <input type="submit" value="发送">
</form>

PHP code (submit.php):

// 收集表单数据
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// 验证表单数据(可省略)

// 将表单数据发送至邮箱
$to = "youremail@example.com";
$subject = "联系表单请求来自 $name";
$body = "邮箱地址:$email\n留言:$message";

mail($to, $subject, $body);

// 输出成功消息
echo "感谢您的留言。我们将在 24 小时内回复您。";

The above is the detailed content of How to build a form using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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