Creating a very simple 1 username/password login in php

后端 未结 5 1070
甜味超标
甜味超标 2020-12-04 22:52

I want to make a single login for just 1 user without storing in a database but I can\'t seem to get this to work.

My code: login.php


&         


        
相关标签:
5条回答
  • 2020-12-04 23:11

    Firstly, you need to put session_start(); before any output to the browser, normally at the top of the page. Have a look at the manual.

    Second, this won't affect your results, but these lines aren't being used anywhere and should be removed:

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

    ...and the last two lines there wouldn't work, you need to put the quotes inside the square brackets:

    $username = $_POST['username'];
    

    If you put session_start() at the top of your page (i.e. before the <html> tag etc), this should work fine.

    0 讨论(0)
  • 2020-12-04 23:18

    Your code could look more like:

    <?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>
    

    Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

    0 讨论(0)
  • 2020-12-04 23:18
    <?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
    
    0 讨论(0)
  • 2020-12-04 23:24

    Here is a simple php script for login and a page that can only be accessed by logged in users.

    login.php

    <?php
        session_start();
        echo isset($_SESSION['login']);
        if(isset($_SESSION['login'])) {
          header('LOCATION:index.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 ( only logged in users can access it )

    <?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>
    
    0 讨论(0)
  • 2020-12-04 23:28

    Your code could look more like:

    <?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>
    
    0 讨论(0)
提交回复
热议问题