search
HomeBackend DevelopmentPHP TutorialHow to use PHP to implement form validation and submission functions

如何使用 PHP 实现表单验证和提交功能

How to use PHP to implement form validation and submission functions

Overview:
In website development, forms are one of the important ways to interact with users. Forms are often used to collect information from users or receive feedback from users. In order to ensure the legality and integrity of the data submitted in the form, we need to verify the form. This article will introduce how to use PHP to implement form validation and submission functions, and provide relevant code examples.

Step 1: Create HTML form
First, we need to create an HTML form to collect user input data. The sample code is as follows:

<!DOCTYPE html>
<html>
<head>
<title>表单验证和提交示例</title>
</head>
<body>
<h2 id="用户信息">用户信息</h2>

<form action="submit.php" method="post">
  <label for="name">姓名:</label>
  <input type="text" id="name" name="name" required><br><br>

  <label for="email">邮箱:</label>
  <input type="email" id="email" name="email" required><br><br>

  <label for="phone">电话:</label>
  <input type="tel" id="phone" name="phone" required><br><br>

  <input type="submit" value="提交">
</form>

</body>
</html>

Step 2: Create a PHP script file
Next, we need to create a PHP script file to validate the form data and submit it to the server. The sample code is as follows (the file name is submit.php):

<!DOCTYPE html>
<html>
<head>
<title>表单验证和提交示例</title>
</head>
<body>

<h2 id="提交结果">提交结果</h2>

<?php
// 验证表单数据
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];

$errors = [];

// 验证姓名
if (empty($name)) {
  $errors[] = "姓名不能为空";
}

// 验证邮箱
if (empty($email)) {
  $errors[] = "邮箱不能为空";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $errors[] = "邮箱格式不正确";
}

// 验证电话
if (empty($phone)) {
  $errors[] = "电话不能为空";
} else if (!preg_match('/^d{11}$/', $phone)) {
  $errors[] = "电话格式不正确";
}

// 如果有错误,则显示错误信息
if (!empty($errors)) {
  foreach ($errors as $error) {
    echo "<p>{$error}</p>";
  }
} else {
  // 执行提交操作
  // ...

  echo "<p>提交成功</p>";
}
?>

</body>
</html>

Step 3: Form verification
In the above code, we obtain the form submission through PHP's $_POST super global variable data and verify it. If the data does not meet the requirements, error information is added to the $errors array. The specific verification rules are as follows:

  • The name cannot be empty
  • The email address cannot be empty and must be a legal email format
  • The phone number cannot be empty and must be It is an 11-digit number

Step 4: Submit operation
If all the data in the form is verified, you can perform the relevant submission operation. Here is only a simple success tip. In actual operation, you may need to store data in the database or send emails.

Summary:
Through the above steps, we can use PHP to implement form verification and submission functions. In actual development, we can conduct more detailed verification of form fields and add more submission operations according to specific needs. This ensures that we receive valid and complete data from our users.

Note: Due to security risks in modern website development, we strongly recommend dual verification on both front-end and back-end to enhance the security of the website.

The above is the detailed content of How to use PHP to implement form validation and submission functions. 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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor