簡體   English   中英

在 php 中創建一個非常簡單的 1 用戶名/密碼登錄

[英]Creating a very simple 1 username/password login in php

我想只為 1 個用戶進行一次登錄而不存儲在數據庫中,但我似乎無法讓它工作。

我的代碼:login.php

<html>
<head>
    <title>Login</title>
</head>
    <h3>Add entry</h3>
    <p> Add another Article</p>
    <form action="trylog.php" method = "post">
        <label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br />
        <label for="password">Password:</label> <input type="text" id="password" name="password"><br /><br />
        <button type = "submit">Login</button>
    </form>
</html>

嘗試日志文件

<html>
    <title>Login</title>
    <body>
        <?php
        $usr = "admin";
        $psw = "password";
        $username = '$_POST[username]';
        $password = '$_POST[password]';
        //$usr == $username && $psw == $password
        session_start();
        if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password")) {
            echo "password accepted";
            $_SESSION['login']=true;
        }else {
            echo "incorrect login";
        }
        ?>

        <form name="input" action="adminportal.php" method="get">
            <input type="submit" value="Home">
        </form>
    </body>
</html>

您的代碼可能看起來更像:

<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
  $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
  if(!$validUser) $errorMsg = "Invalid username or password.";
  else $_SESSION["login"] = true;
}
if($validUser) {
   header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Login</title>
</head>
<body>
  <form name="input" action="" method="post">
    <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
    <label for="password">Password:</label><input type="password" value="" id="password" name="password" />
    <div class="error"><?= $errorMsg ?></div>
    <input type="submit" value="Home" name="sub" />
  </form>
</body>
</html>

現在,當基於header('LOCATION:wherever.php)重定向頁面時,將session_start()放在頁面頂部並測試以確保$_SESSION['login'] === true 請記住, ==將是真實的,如果$_SESSION['login'] == 1為好。 當然,出於安全原因,這是一個壞主意,但我的示例可能會教您另一種使用 PHP 的方式。

這是一個用於登錄的簡單 php 腳本和一個只能由登錄用戶訪問的頁面。

登錄.php

<?php
    session_start();
    echo isset($_SESSION['login']);
    if(isset($_SESSION['login'])) {
      header('LOCATION:admin.php'); die();
    }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <?php
      if(isset($_POST['submit'])){
        $username = $_POST['username']; $password = $_POST['password'];
        if($username === 'admin' && $password === 'password'){
          $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
        } {
          echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
        }
        
      }
    ?>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

admin.php (只有登錄用戶才能訪問)

<?php
    session_start();
    if(!isset($_SESSION['login'])) {
        header('LOCATION:login.php'); die();
    }
?>
<html>
    <head>
        <title>Admin Page</title>
    </head>
    <body>
        This is admin page view able only by logged in users.
    </body> 
</html>

首先,你需要把session_start(); 在任何輸出到瀏覽器之前,通常在頁面頂部。 看看說明書。

其次,這不會影響您的結果,但這些行沒有在任何地方使用,應該刪除:

$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';

...最后兩行不起作用,您需要將引號放在方括號內:

$username = $_POST['username'];

如果您將session_start()放在頁面頂部(即<html>標記之前等),這應該可以正常工作。

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in

您的代碼可能看起來更像:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
    <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
    <div class='error'><?php echo $userError;?></div>
    <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
    <div class='error'><?php echo $passError;?></div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM