Home  >  Article  >  Backend Development  >  刚开始自学php,关于表单验证,不明白,求帮忙,该怎么处理

刚开始自学php,关于表单验证,不明白,求帮忙,该怎么处理

WBOY
WBOYOriginal
2016-06-13 12:11:18950browse

刚开始自学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;
}
?>


在用户提交该表单时,我们还要做两件事:
(通过 PHP trim() 函数)去除用户输入数据中不必要的字符(多余的空格、制表符、换行)
(通过 PHP stripslashes() 函数)删除用户输入数据中的反斜杠(\)
他说这个样子可我根本不明白,怎么实现的,能不能来个详细注释,
------解决思路----------------------
举个例子,$str="   hello   ",hello前后有三个空格,你可以用echo strlen($str)看到是有11个字符的,如果echo strlen(trim($str))看到就只有5个字符,因为前后的三个空格被去掉了...

 stripslashes()  也就是你说的去掉数据中存在的反斜杠,对应的有addslashes,对引号转移,也就是添加反斜杠,比如存在嵌套的引号时。

 htmlspecialchars 就是把一些特殊字符进行转码,从而不按本身来显示,比如

你自己实际操作一下就明白了,这些都是基础
------解决思路----------------------
1.trim
把字符傳兩邊的空格去掉。
例如
$str = '   abc  ' ;
echo $str; // '  abc  ';
echo trim($str); 'abc'

2.stripslashes
返回一个去除转义反斜线后的字符串(\' 转换为 ' 等等)。双反斜线(\\)被转换为单个反斜线(\)。 

例如特殊字符," ' \ 等,直接寫入mysql 是會報錯的,所以要對這些字符轉義 \要寫\\, '要寫成\'  "要寫成\" 才能正常使用。

而stripslashes的作用就是把轉義還原。
\' 轉為 '
\\ 轉未 \
\" 轉為 "

3.htmlspecialchars
html的標記轉義
例如你有個字符是
如果你直接輸出,在頁面上是看不到東西,因為是html標記,會被瀏覽器解釋。
所以就需要用到htmlspecialchars,把html標記轉為字符串。
轉義規則如下:
'&' (ampersand) becomes '&'  
2.  '"' (double quote) becomes '"' when ENT_NOQUOTES  is not set.  
3.  "'" (single quote) becomes ''' (or ') only when ENT_QUOTES  is set.  
4.  '
所以使用htmlspecialchars后會轉義為 

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