-4

我想使用 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>
4

1 回答 1

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   
}
于 2013-10-18T08:39:51.023 回答