使用PHP进行表单验证并显示输入的用户名隐藏表单输入字段

时间:2013-10-18 08:32:12

标签: php html

我想使用php验证用户名和密码,然后在同一页面中显示用户名代替隐藏整个div字段集。 我在字段集内部采用了表单输入字段,这都在div中。

PHP:
<?php       //------------------------------------------------------------------------------>PHP VALIDATION
    $user="";
    $pass="";
    $nameErr="";
    $passErr="";`enter code here`
    //$pattern='/^[a-zA-Z0-9@_ ]*$/';
    if($_SERVER['REQUEST_METHOD']=='POST')
    {
        if(empty($_POST['uname']))
        {
            $nameErr='Enter Your Name!';
        }
        else
        {
            $user = test_input($_POST['uname']);
            if(!preg_match('/^[a-zA-Z0-9@_]*$/',$user))
            {
                $nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,@_ are allowed)';
            }
        }
    }

    function test_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>


HTML:

<div class='input'>
    <fieldset>
        <?php echo $user;?>
        <form method='post' name='f1' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
            <table>
                <tr>
                    <td>
                        User Name:<input type='text' id='uname' name='uname' class='uname' placeholder='USERNAME' autocomplete='off' autofocus><span class='error'>*</span>
                        Password:<input type='password' id='pass' class='pass' placeholder='PASSWORD' autocomplete='off'><input type='submit' name='submit' id='loggin' value='LOGIN' class='login'>
                    </td>
                </tr>
            </table>
        </form>
    </fieldset>
    <div class='errormsg' id='errmsg'><?php echo $nameErr;?></div>
</div>

1 个答案:

答案 0 :(得分:1)

这是一个相当容易的结构。您需要一个表单,一个会话(或用户名的其他容器)和一些逻辑。请参阅下面的示例代码。我想你可以自己弄清楚其余部分:

<?php
    session_start();

    if(isset($_POST['btn_Login'])) {

        // validation code;

        // if validation succeeded:
        $_SESSION['LoggedIn'] = $_POST['Username'];
    }

    if(isset($_SESSION['LoggedIn'])) {

        echo 'Welcome ' . $_SESSION['LoggedIn'];
?>
// display contents when logged in
<?php   
    } else { 
?>
// display form (where the field for the username is named 'Username' and the submitbutton is named 'btn_Login')
<?php   
}