PHP Form Tutorial (2)

【Foreword】

       On the basis of the previous article PHP form tutorial (1)  , today I will continue to summarize the knowledge points related to PHP forms, and record and summarize here.

 

【List】

 (1) Form validation security related

         Contains PHP form security, super global variable $_SERVER["PHP_SELF"] , htmlspecialchars (special characters) function

 (2) Validate form data

 (3) Form required validation and error prompts

 (4) Form data validation and error prompts

 (5) Prevent the form from being emptied after submitting the data

 (6) Complete form instance

 

【main body】

 (1) Form validation security related

Security is very important when dealing with PHP forms. The following describes how to handle PHP forms securely.

Proper validation of HTML form information is important to prevent spam and hackers.

 

   ①Form validation case

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    Website: <input type="text" name="website"><br>
    Comment: <textarea name="comment" rows="5" cols="40"></textarea><br>
Gender:
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="male">Male
</form>

    When this form is submitted, send the form data with method="post"

    ②What is the $_SERVER["PHP_SELF"] variable?

     $_SERVER["PHP_SELF"] is a superglobal variable that returns the filename of the currently executing script. So instead of jumping to another page, the form data is sent to the page itself. In this way, the user can get the error message on the form page.

     ③What is the htmlspecialchars() function?

     Function to convert special characters to HTML entities. This means that HTML characters like < and > are replaced with < and > . This prevents attackers from exploiting the code by injecting HTML or JavaScript code in the form (cross-site scripting attack). The following is an introduction to website security

     ④PHP form security

     $_SERVER["PHP_SELF"] variable can be exploited by hackers! If your page uses PHP_SELF, the user can enter an underscore and then execute cross-site scripting (XSS) . I will introduce XSS in a later article.

      黑客可以在地址栏中键入更改的URL,在其后植入一段脚本,当此页面加载后,就会执行代码。而且<script> 标签内能够添加任何JS代码(15-50k)!黑客能够把用户重定向到另一台服务器上的某个文件,该文件中的恶意代码能够更改全局变量或将表单提交到其他地址以保存用户数据,等等

     注意:不要用Chrome测试,因为Chrome会自动拦截,踩了一下午坑才查出来问题是浏览器拦截

     ⑤如果避免 $_SERVER["PHP_SELF"] 被利用?

   通过使用 htmlspecialchars(html特殊字符) 函数能够避免 $_SERVER["PHP_SELF"] 被利用,

   原理:htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体,如果用户试图利用 PHP_SELF 变量,会输出实体字符,使得植入的脚本无法执行

   & (和号) 成为 &

   " (双引号) 成为 "

   ' (单引号) 成为 '

   < (小于) 成为 <

   > (大于) 成为 >

     

(2)验证表单数据

   了解了表单验证安全相关后,我们要做的第一件事是通过 PHP 的 htmlspecialchars() 函数传递所有变量。

   在我们使用 htmlspecialchars() 函数后,如果用户试图在文本字段中提交以下内容:

<script>location.href('http://www.baidu.com')</script>

   即使这样导入脚本,代码不会执行,因为会被保存为转义代码,就像这样:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

   在用户提交该表单时,我们还要做两件事:

       ①去除用户输入数据中不必要的字符(多余的空格、制表符、换行,通过 PHP trim() 函数)

       ②删除用户输入数据中的反斜杠(\,通过 PHP stripslashes() 函数)

    接下来我们创建一个检查函数test_input(相比一遍遍地写代码,这样效率更好)。现在,我们能够通过 test_input() 函数检查每个 $_POST 变量,脚本是这样的:

    案例:

<!DOCTYPE html>
<html>
<title>PHP测试demo</title>
<style type="text/css">
        *{margin:0;padding:0}
</style>
<body>
<?php
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   $email = test_input($_POST["email"]);
   $website = test_input($_POST["website"]);
   $comment = test_input($_POST["comment"]);
   $gender = test_input($_POST["gender"]);
}
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>
<h2>PHP 验证实例</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   姓名:<input type="text" name="name">
   <br><br>
   电邮:<input type="text" name="email">
   <br><br>
   网址:<input type="text" name="website">
   <br><br>
   评论:<textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   性别:
   <input type="radio" name="gender" value="female">女性
   <input type="radio" name="gender" value="male">男性
   <br><br>
   <input type="submit" name="submit" value="提交">
</form>
<?php
echo "<h2>您的输入:</h2>";
echo $name."<br>";
echo $email."<br>";
echo $website."<br>";
echo $comment."<br>";
echo $gender;
?>
</body>
</html>

   代码详解:

   ①超全局变量$_SERVER的元素$_SERVER['REQUEST_METHOD'],作用:返回访问页面使用的请求方法(例如 POST)

    ②$_POST 变量用于收集来自 method=”post” 的表单中的值

$_POST 变量是一个数组,内容是由 HTTP POST 方法发送的变量名称和值。$_POST 变量用于收集来自 method=”post” 的表单中的值,带有 POST 方法的表单发送的信息,任何人都是不可见的(不会显示在浏览器的地址栏),并且对发送信息的量也没有限制

 

(3)表单必填验证及错误提示

   在上面的例子中,所有输入字段都是可选的。即使用户未输入任何数据,脚本也能正常工作。接下来制作必填输入字段,并创建需要时使用的错误消息。

   在下面的代码中我们增加了新变量:$nameErr。错误变量会保存被请求字段的错误消息,接下来为每个 $_POST 变量添加了一个 if else 语句。这条语句检查 $_POST 变量是否为空(通过 PHP empty() 函数)。如果为空,则错误消息会存储于不同的错误变量中。如果不为空,则通过 test_input() 函数发送用户输入数据:

   案例:

<!DOCTYPE html>
<html>
<title>PHP测试demo</title>
<style type="text/css">
        *{margin:0;padding:0}
        .error {color: #FF0000;}
    </style>
<body>
<?php
// 定义变量并设置为空值
$nameErr = = "";
$name =  = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "姓名是必填的";
   } else {
     $name = test_input($_POST["name"]);
   }
}
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>
<h2>PHP 验证实例</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   姓名:<input type="text" name="name">
   <span class="error">* <?php echo $nameErr;?></span><br>
   <input type="submit" name="submit" value="提交">
</form>
<?php
echo "<h2>Your input:</h2>";
echo $name;
?>
</body>
</html>
   Detailed explanation:

   In the last case, there is another problem: when the function to check the data is placed behind the HTML layout tag, it will run abnormally, and the doubt has not been solved yet? ?

 

(4) Form data validation and error prompts

   Next comes validation of specific input data such as "Does the Name field contain only letters and spaces?" and "Does the E-mail field contain valid email address syntax?", and if the Website field is filled, "Does this field contain a valid URL?" etc.

   For example to verify the name:

   The following code shows a simple way to check if the name field contains letters and spaces. If the name field is invalid, an error message is stored. The preg_match() function retrieves the pattern of the string and returns true if the pattern exists, false otherwise

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   if (!preg_match("/^[a-zA-Z ]*$/",$name)) {//Retrieve the pattern of the string
     $nameErr = "Only letters and spaces are allowed!";
   }else if(empty($name)){
     $nameErr = "nulls not allowed";
   }else{
        $name = test_input($_POST["name"]);
   }
}
   Note: In addition to the if...elseif....else conditional statement execution, I also tried switch, but with limitations (switch can only pass one value)

 

(5) Next, I will explain how to prevent the form from emptying all input fields after the user submits the form 

The following is a detailed explanation of retaining the value in the input field after submitting the form

   If you want to keep the displayed submitted data, just add a small PHP script to the value attribute of the input field, for example

姓名:<input type="text" name="name" value="<?php echo $_POST["name"]?>">
  In addition, attach a piece of code to prevent radio selection from emptying:
<input type="radio" name="gender"
   <?php if (isset($gender) && $gender=="female") echo "checked";?>
   value="female">Female
   <input type="radio" name="gender"
   <?php if (isset($gender) && $gender=="male") echo "checked";?>
   value="male">Male<br>
   Code analysis: isset() is generally used to detect whether a variable is set, such as whether the radio is selected or not

 

(6) Complete form instance

<!DOCTYPE HTML>
<html>
<head>
<title>PHP测试demo</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variable and set to null
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // Check if name contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "只允许字母和空格"; 
     }
   }
   if (empty($_POST["email"])) {
     $emailErr = "电邮是必填的";
   } else {
     $email = test_input($_POST["email"]);
     // 检查电子邮件地址语法是否有效
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
       $emailErr = "无效的 email 格式"; 
     }
   }
   if (empty($_POST["website"])) {
     $website = "";
   } else {
     $website = test_input($_POST["website"]);
     // 检查 URL 地址语法是否有效(正则表达式也允许 URL 中的斜杠)
     if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*
        [-a-z0-9+&@#\/%=~_|]/i",$website)) {
       $websiteErr = "无效的 URL"; 
     }
   }
   if (empty($_POST["comment"])) {
     $comment = "";
   } else {
     $comment = test_input($_POST["comment"]);
   }
   if (empty($_POST["gender"])) {
     $genderErr = "性别是必选的";
   } else {
     $gender = test_input($_POST["gender"]);
   }
}
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>
<h2>PHP 验证实例</h2>
<p><span class="error">* 必需的字段</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   姓名:<input type="text" name="name">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   电邮:<input type="text" name="email">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   网址:<input type="text" name="website">
   <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   评论:<textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   性别:
   <input type="radio" name="gender" value="female">女性
   <input type="radio" name="gender" value="male">男性
   <span class="error">* <?php echo $genderErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="提交"> 
</form>
<?php
echo "<h2>您的输入:</h2>";
echo $name."<br>";
echo $email."<br>";
echo $website."<br>";
echo $comment."<br>";
echo $gender;
?>
</body>
</html>
 

 

 

【总结】

(1)PHP常用函数

     ①empty()检验是否为空;

         对比:isset()一般用来检测变量是否设置,例如单选是否选定状态

     ②htmlspecialchars() 把一些预定义的字符转换为 HTML 实体

     ③trim()去除输入数据中不必要的字符(多余的空格、制表符、换行)

     ④stripslashes()去除输入数据中的反斜杠(\)

     ⑤preg_match() 检索字符串的模式,如果模式存在则返回 true,否则返回 false

(2)变量

     ①预定义的 $_POST 变量用于收集来自 method="post" 的表单中的值

     ②超全局变量$_SERVER,许多属性,以下列举了几个常见的

     ③$_SERVER["PHP_SELF"] 是一种超全局变量,它返回当前执行脚本的文件名

     ④$_SERVER['REQUEST_METHOD']超全局变量,返回访问页面使用的请求方法(例如 POST)

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326164372&siteId=291194637