Table of Contents
PHP 表单验证实例
您输入的内容是:
Home Backend Development PHP Tutorial PHP form learning form input and verification

PHP form learning form input and verification

Oct 29, 2021 am 10:38 AM
php form input form validation

In the previous article, I brought you "How to set and obtain PDO attributes in PHP database learning?" ", which introduces in detail the relevant knowledge of how to set and obtain PDO attributes in PHP. In this article, we will take a look at the related issues of PHP forms. I hope it will be helpful to everyone!

PHP form learning form input and verification

In the previous article we have already understood the basics of PHP, including the $_GET and $_POST variables, They are used to retrieve information in forms. The knowledge points that need our attention are PHP form user input and form validation. Then let's take a look at the related knowledge of form input and form validation in PHP.

PHP forms and user input

To understand PHP forms and user input, first we need to understand what It's a form. To be precise, a Web form is an interactive platform, and its main function is to provide an interactive platform between viewers and the website. Forms are mainly used in web pages to send data to the server.

For example, the form used when registering information needs to be submitted when you fill in the information. Submission at this time is to transfer the content on the form when you register from the client browser to the server, and then through PHP After the program is processed, the information required by the user is passed back to the client browser. By obtaining the user's information, PHP and the Web form can interact. It just provides such an interactive platform.

Next, let’s take a look at the form through an example. The example is as follows:

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>PHP中文网</title>
 </head>
 <body>
 
 <form action="form.php" method="post">
     名字: <input type="text" name="fname"><br>
     年龄: <input type="text" name="age"><br>
     <input type="submit" value="提交">
 </form>
 
 </body>
 </html>
Copy after login

What we need to pay attention to is that the form belongs to HTML. For more related knowledge, you can click "HTMLTutorial" to study, the running results of the above example:

PHP form learning form input and verification

This is what we call the form, then we are in it Where will the filled-in information, that is, the form information be sent? When we click submit, the data in the form will be sent to the form.php page in the form of POST.

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 echo "欢迎你:".$_POST["fname"] ."<br/>";
 echo "你的年龄是:".$_POST[&#39;age&#39;];
 ?>
Copy after login

The running results we send to from.php are as follows:

PHP form learning form input and verification

When the user input is completed, the form needs to be verified at this time Now, user input should be validated via client-side script whenever possible. Browser validation is faster and reduces the load on the server.

If user input needs to be inserted into the database, you should consider using server validation. A good way to validate a form on the server is to pass the form to itself, rather than jumping to a different page. This way users can get error messages on the same form page. It will be easier for users to find errors. So let’s take a look at the related knowledge of form validation.

PHP Form Validation

We need to consider security when processing PHP forms. We will demonstrate the secure processing of PHP form data. In order to prevent hackers and spam, we need to perform data security verification on the form. Next, let's take a look at the required and optional text fields, radio buttons, and submit buttons in the form through examples.

The example is as follows:

<!DOCTYPE HTML>
 <html>
 <head>
     <meta charset="utf-8">
     <title>PHP.cn</title>
 </head>
 <body>
 <h2 id="PHP-nbsp-表单验证实例">PHP 表单验证实例</h2>
 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
    名字: <input type="text" name="name" value="">
     <br>
     E-mail: <input type="text" name="email" value="">
     <br>
     网址: <input type="text" name="website" value="">
     <br>
     备注: <textarea name="comment" rows="5" cols="40"></textarea>
     <br>
     性别:
     <input type="radio" name="gender"  value="female">女
     <input type="radio" name="gender"  value="male">男
     <br>
     <input type="submit" name="submit" value="提交">
 </form>
 </body>
 </html>
Copy after login

Output result:

PHP form learning form input and verification

What we need to pay attention to is that the different fields are Different validation rules, the validation rules for different fields in the above example are as follows:

The validation rules for names are required and can only contain letters and spaces. The E-mail validation rule is required, which must be a valid email address (containing '@' and '.'). The URL validation rule is optional, and if present, it must contain a valid URL. Validation rules for notes are optional, multi-line input fields. A gender validation rule is required and one must be selected.

Let’s take a look at the knowledge used in the above example:

<span style="max-width:90%"><strong>$_SERVER["PHP_SELF"] </strong></span> Variable

$_SERVER["PHP_SELF"] is a super global variable that returns the file name of the currently executing script. Therefore, $_SERVER["PHP_SELF"] sends the form data to the page itself instead of jumping to another page. In this way, users can get error message information on the form page.

<strong><span style="font-size: 16px;">htmlspecialchars()</span></strong>## Function

htmlspecialchars() 函数把特殊字符转换为 HTML 实体。这意味着 < 和 > 之类的 HTML 字符会被替换为 < 和 > 。这样可防止攻击者通过在表单中注入 HTML 或 JavaScript 代码(跨站点脚本攻击)对代码进行利用。

其中我们需要注意的是:

$_SERVER["PHP_SELF"] 变量能够被黑客利用,如何避免 $_SERVER["PHP_SELF"] 被利用?

$_SERVER["PHP_SELF"] 可以通过 htmlspecialchars() 函数来避免被利用。

form 代码如下所示:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Copy after login

htmlspecialchars() 把一些预定义的字符转换为 HTML 实体。现在如果用户想利用 PHP_SELF 变量, 结果将输出如下所示:

<form method="post" action="test_form.php/"><script>alert(&#39;hacked&#39;)</script>">
Copy after login

尝试该漏洞失败!

通过PHP验证表单数据

我们要做的第一件事是通过 PHP 的 htmlspecialchars() 函数传递所有变量。在用户提交该表单时,我们还要做两件事:

首先通过 PHP trim() 函数去除用户输入数据中不必要的字符,比如多余的空格、制表符、换行等,然后通过 PHP stripslashes() 函数删除用户输入数据中的反斜杠(\)。接下来我们创建一个检查函数,我们把函数命名为 test_input()。最后我们能够通过 test_input() 函数检查每个 $_POST 变量。

我们将验证程序可以放到上述示例中去,示例如下:


 
 
     
     PHP中文网(php.cn)
 
 
 
 
 
 

PHP 表单验证实例

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 名字:

E-mail:

网址:

备注:

性别:

您输入的内容是:"; echo $name; echo "
"; echo $email; echo "
"; echo $website; echo "
"; echo $comment; echo "
"; echo $gender; ?>
Copy after login

输出结果:

PHP form learning form input and verification

其中我们需要注意的是:

我们在执行以上脚本时,会通过$_SERVER["REQUEST_METHOD"]来检测表单是否被提交 。如果 REQUEST_METHOD 是 POST, 表单将被提交 - 数据将被验证。如果表单未提交将跳过验证并显示空白。在以上实例中使用输入项都是可选的,即使用户不输入任何数据也可以正常显示。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of PHP form learning form input and verification. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles