首页 > 解决方案 > 任何人都可以帮助我使用带有 HTML 的登录表单 PHP 吗?

问题描述

我在将我的 PHP 代码集成到我的 HTML 代码时遇到了一些麻烦!任何人都可以帮助或指出我正确的方向吗?

这是我的 HTML 代码:

  <h2>Enter Username and Password</h2> 
  <div class = "container form-signin">
     
    
  </div> <!-- /container -->
  
  <div class = "container">
  
     <form class = "form-signin" role = "form" 
        action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); 
        ?>" method = "post">
        <h4 class = "form-signin-heading"><?php echo $msg; ?></h4>
        <input type = "text" class = "form-control" 
           name = "username" placeholder = "username = tutorialspoint" 
           required autofocus></br>
        <input type = "password" class = "form-control"
           name = "password" placeholder = "password = 1234" required>
        <button class = "btn btn-lg btn-primary btn-block" type = "submit" 
           name = "login">Login</button>
           
     </form>
            
     Click here to clean <a href = "logout.php" tite = "Logout">Session.
     
     
  </div> 
  

我的 PHP 代码是

 <?php
        $msg = '';
        
        if (isset($_POST['login']) && !empty($_POST['username']) 
           && !empty($_POST['password'])) {
            
           if ($_POST['username'] == 'tutorialspoint' && 
              $_POST['password'] == '1234') {
              $_SESSION['valid'] = true;
              $_SESSION['timeout'] = time();
              $_SESSION['username'] = 'tutorialspoint';
              
              echo 'You have entered valid use name and password';
           }else {
              $msg = 'Wrong username or password';
           }
        }
     ?>

我想请写一个登录用户,然后只允许他访问,登录可以授权这个页面。

标签: phphtmlauthenticationpasswords

解决方案


对于一个非常简单的登录,一切都是正确的。但是您必须在代码中session_start()使用变量之前调用函数$_SESSION(在登录页面或其他页面中)。绝对对于真正的登录页面,您需要连接到数据库等等......

<?php
    $msg = '';

    if (isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password'])) {
        if ($_POST['username'] == 'tutorialspoint' && $_POST['password'] == '1234') {
            session_start();
            $_SESSION['valid'] = true;
            $_SESSION['timeout'] = time();
            $_SESSION['username'] = 'tutorialspoint';

            echo 'You have entered valid use name and password';
        }else {
            $msg = 'Wrong username or password';
        }
    }
?>

推荐阅读