首頁  >  文章  >  每日程式設計  >  PHP怎麼過濾post提交資料中的空格

PHP怎麼過濾post提交資料中的空格

藏色散人
藏色散人原創
2018-10-24 11:13:049007瀏覽

本篇文章主要介紹PHP如何將post提交過來的資料進行空格過濾。

大家應該都知道,我們在開發登入介面時,除了前台的一些js驗證,還有一些提交資料到後台後的驗證。

那麼關於登入介面form表單提交的前台驗證方法,在這兩篇文章【jQuery表單驗證提交:前台驗證一】【jQuery表單驗證提交:前台驗證二】中也跟大家進行相關的介紹了,需要的朋友可以選擇參考。

下面我就透過簡單的程式碼範例,跟大家介紹php後台過濾資料空格驗證的方法。

1、login.html程式碼範例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>登录</title>
    <style type="text/css">
        body {
            background: url(images/bg.png);
        }

        .login {
            width: 370px;
            margin: 100px auto 0px;
            text-align: center;
        }

        #username{
            width: 360px;
            height: 50px;
            border: none;
            background: #fff;
            border-radius: 10px;
            margin: 5px auto;
            padding-left: 10px;
            color: #745A74;
            font-size: 15px;
        }

        #password{
            width: 360px;
            height: 50px;
            border: none;
            background: #fff;
            border-radius: 10px;
            margin: 5px auto;
            padding-left: 10px;
            color: #745A74;
            font-size: 15px;
        }

        .botton {
            width: 130px;
            height: 40px;
            background: #745A74;
            border-radius: 10px;
            text-align: center;
            color: #fff;
            margin-top: 30px;
            line-height: 40px;
        }
    </style>
</head>
<body>
<div class="login">
    <form action="check1.php" method="post">
        <img  src="images/header.png" alt="PHP怎麼過濾post提交資料中的空格" ><br>
        <input type="text" id="username" name="username" placeholder="请输入用户名!" value=""><br>
        <input type="password" id="password" name="password" placeholder="请输入密码!" value=""><br>
        <input type="submit" class="botton" onclick="add()" value="login">
    </form>
</div>
</body>
</html>

這裡的form表單主要是透過post方式提交資料到check1.php。

2、check1.php程式碼範例:

<?php
$arr = [&#39;admin&#39;];


if (in_array(trim($_POST[&#39;username&#39;]),$arr)){
    echo "登录成功!";
}else{
    echo "用户名不存在!";
}
var_dump($_POST[&#39;username&#39;]);
var_dump(trim($_POST[&#39;username&#39;]));

前台登入介面效果如下圖:

PHP怎麼過濾post提交資料中的空格

如果我們將上述check1.php程式碼中trim函數刪除掉。

註:trim() 函數表示移除字串兩側的空白字元或其他預定義字元。

那麼當我們輸入帶空格的用戶名,結果就如下圖:

PHP怎麼過濾post提交資料中的空格

如圖顯示用戶名不存在,這是由於我們後台沒有進行過濾資料空格的操作。

當我們按照上述check1.php的完整程式碼來處理提交過來的數據,那麼即使是帶有空格的用戶名,都會顯示登入成功。

效果如下:

PHP怎麼過濾post提交資料中的空格

#如圖我們成功過濾了使用者名稱前後的空格。

其實在我們日常登入各種後台的過程中,想必有一部分朋友都習慣在輸入使用者名稱或密碼時隨手加空格。那麼大家可以根據自身項目的需求,來決定是否需要進行過濾空格的操作。

這篇文章就是關於PHP將post提交過來的資料進行空格過濾的方法介紹,簡單易懂,希望對需要的朋友有所幫助!

想要了解更多PHP知識,可以關注PHP中文網PHP影片教學,歡迎大家參考學習!

以上是PHP怎麼過濾post提交資料中的空格的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn