剛開始自學php,關於表單驗證,不明白,求幫忙

來源:互聯網
上載者:User
// 定義變數並設定為空白值
$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() 函數)刪除使用者輸入資料中的反斜線(\)
他說這個樣子可我根本不明白,怎麼實現的,能不能來個詳細注釋,


回複討論(解決方案)

功能你自己都說出來了,還有什麼不明白的?post提交的,就用post接收。。。。。 test_input 不過是一個簡單的過濾函數而已

舉個例子,$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. '<' (less than) becomes '<'
5. '>' (greater than) becomes '>'

所以使用htmlspecialchars後???? <html>

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.