How to build a form in PHP? Create a form using the <form> tag, specifying the action and method attributes. Collect user input, including text, email, radio buttons, and checkboxes, through the 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.
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 <form>
tag. The <form>
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!