douxu2081 2019-02-02 15:39
浏览 91

如何正确使用PHP会话变量来执行用户登录?

When the user goes to my website after the user logins in on this page they are then presented with this page. However, if I type in the full URL webbrowserinfo.96.lt/logindone/logincode/V1/homepage.php it loads regardless if the user logins in or not. From doing my own tests it has something to do with the log out button.

Therefore, I added the code below to prevent the user from typing the full file path of the protected page and bypassing the login. However, now my index page (login page) doesn't work when the user types in the correct user login information.

All I want is for the user to be able to login with the correct login details which is "Username: liam" and "Password: 1" and then see the login protected page. Once they get on that page click the "signout" button and be sent the the index.php page.

<?php
//check if session id is set. If it is not set, user will be redirected back to login page

if(!isset($_SESSION['username'])){
     header('Location:index.php');
     die();
}
?>

My website has three scripts here they're if you need to see them

BELOW IS THE LOGIN PAGE CODE

<?php
   //PHP method to use cache memory to store details
   session_start();
   //Makes the "config.php" file available to be executed from this page
   require_once('dbconfig/config.php');
   ?>
<!DOCTYPE html>
<html>
   <head>
      <!-- Site title, CSS external file and font awesome -->
      <title>Login Page - Created by Liam Docherty</title>
      <link rel="stylesheet" href="css/design.css">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
   </head>
   <body>
      <div id="main-wrapper">
         <center>
            <h2>Login Form - Created by Liam Docherty</h2>
         </center>
         <div class="imgcontainer">
            <img src="imgs/icon-person-512.png" alt="Avatar" class="avatar">
         </div>
         <!-- THE FORM -->
         <!-- action="index.php" -- This attribute shows where the PHP script that does the processing is located -->
         <!-- method="post" -- The attribute identifies the action that will be performed with the data of the form. I.E. POST data to the "users" database -->
         <form action="index.php" method="post">
            <div class="inner_container">
               <label><b>Username</b></label>
               <input type="text" placeholder="Enter Username" name="username" required>
               <label><b>Password</b></label>
               <input type="password" placeholder="Enter Password" name="password" required>
               <!-- The Login button -->
               <button class="login_button" name="login" type="submit">Login</button>
               <!-- The button that is linked to the "register.php" page -->
               <a href="register.php"><button type="button" class="register_btn">Register</button></a>
            </div>
         </form>
         <?php
            //Condition, checking the Login button is pressed
            if(isset($_POST['login']))
            {
                //The data from the Form (username & password) is stored into the @$username & @$passwordVariables
                //You use @ before a VARIABLE in PHP when you do not want to initialise the VARIABLE before using it
                @$username=$_POST['username'];
                @$password=$_POST['password'];

                //Statement that will SELECT the data from the "login" table, WHERE the Usename and Password typed match the typed ones
                //Once the database is checked, if login details match than it stores the data in the "$query" VARIABLE
                $query = "SELECT * FROM login WHERE username='$username' and password='$password' ";
                //echo $query;

                //This statement performs both the connection to the database using the values in the "$con" VARIABLE and
                //The SELECT statement stored in the "$query" VARIABLE
                $query_run = mysqli_query($con,$query);
                //echo mysql_num_rows($query_run);

                //IF the "$query_run" is run successfully, then
                if($query_run)
                {
                    //Check if the Username and Password exist in the database, if they exist
                    if(mysqli_num_rows($query_run)>0)
                    {
                    $row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);

                    $_SESSION['username'] = $username;
                    $_SESSION['password'] = $password;

                    //Sent the user to the "homepage.php" page
                    header( "Location: homepage.php");
                    }
                    else
                    {
                        //IF NOT, Display the message below
                        echo '<script type="text/javascript">alert("No such User exists. Invalid Credentials")</script>';
                    }
                }

                //IF the "$query_run" is NOT successful, then
                else
                {
                    //Display this message
                    echo '<script type="text/javascript">alert("Database Error")</script>';
                }
            }
            else
            {
            }
            ?>
      </div>
   </body>
</html>

PASSWORD PROTECTED PAGE CODE

This issue with the code below is that it doesn't let me actually login. This is good though as it stops a user just typing in the full file path of the URL and bypassing the login system.

<?php
//check if session id is set. If it is not set, user will be redirected back to login page

if(!isset($_SESSION['username'])){
     header('Location:index.php');
     die();
}
?>

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="">
      <meta name="author" content="">
      <link rel="icon" href="../../../../favicon.ico">
      <!-- Site title, CSS external file and font awesome -->
      <title>Login Page - Created by Liam Docherty</title>
      <link rel="stylesheet" href="css/design.css">
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
   </head>
   <body class="bg-white">
      <div class="container">
         <div class="py-5 text-center">
            <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
            <h2>Checkout form</h2>
            <p class="lead">Below is an example form built entirely with Bootstrap's form controls. Each required form group has a validation state that can be triggered by attempting to submit the form without completing it.</p>
         </div>
         <div class="row">
            <div class="col-md-4 order-md-2 mb-4">
               <h4 class="d-flex justify-content-between align-items-center mb-3">
                  <span class="text-muted">Your cart</span>
                  <span class="badge badge-secondary badge-pill">3</span>
               </h4>
               <ul class="list-group mb-3">
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Product name</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$12</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Second product</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$8</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Third item</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$5</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between bg-light">
                     <div class="text-success">
                        <h6 class="my-0">Promo code</h6>
                        <small>EXAMPLECODE</small>
                     </div>
                     <span class="text-success">-$5</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between">
                     <span>Total (USD)</span>
                     <strong>$20</strong>
                  </li>
               </ul>
               <form class="card p-2">
                  <div class="input-group">
                     <input type="text" class="form-control" placeholder="Promo code">
                     <div class="input-group-append">
                        <button type="submit" class="btn btn-secondary">Redeem</button>
                     </div>
                  </div>
               </form>
            </div>
            <div class="col-md-8 order-md-1">
               <h4 class="mb-3">Billing address</h4>
               <form class="needs-validation" novalidate>
                  <div class="row">
                     <div class="col-md-6 mb-3">
                        <label for="firstName">First name</label>
                        <input type="text" class="form-control" id="firstName" placeholder="" value="" required>
                        <div class="invalid-feedback">
                           Valid first name is required.
                        </div>
                     </div>
                     <div class="col-md-6 mb-3">
                        <label for="lastName">Last name</label>
                        <input type="text" class="form-control" id="lastName" placeholder="" value="" required>
                        <div class="invalid-feedback">
                           Valid last name is required.
                        </div>
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="username">Username</label>
                     <div class="input-group">
                        <div class="input-group-prepend">
                           <span class="input-group-text">@</span>
                        </div>
                        <input type="text" class="form-control" id="username" placeholder="Username" required>
                        <div class="invalid-feedback" style="width: 100%;">
                           Your username is required.
                        </div>
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="email">Email <span class="text-muted">(Optional)</span></label>
                     <input type="email" class="form-control" id="email" placeholder="you@example.com">
                     <div class="invalid-feedback">
                        Please enter a valid email address for shipping updates.
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="address">Address</label>
                     <input type="text" class="form-control" id="address" placeholder="34 Hoxton liam street" required>
                     <div class="invalid-feedback">
                        Please enter your shipping address.
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-5 mb-3">
               <!-- Logout button -->
                <a class="btn btn-primary" href="index.php" role="button">Signout button</a>
               </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
  • 写回答

1条回答 默认 最新

  • dsdv76767671 2019-02-02 16:44
    关注

    My guess is that it's because you have no input names "login". You have a button named so, but not an input. My suggestion it to change it to something like this:

     <form action="index.php" method="post">
                <div class="inner_container">
                   <label><b>Username</b></label>
                   <input type="text" placeholder="Enter Username" name="username" required>
                   <label><b>Password</b></label>
                   <input type="password" placeholder="Enter Password" name="password" required>
                   <input type="hidden" name="login" value="true"> <!-- Not sure a value is really even needed -->
                   <!-- The Login button -->
                   <button class="login_button" type="submit">Login</button>
                   <!-- The button that is linked to the "register.php" page -->
                   <a href="register.php"><button type="button" class="register_btn">Register</button></a>
                </div>
             </form>
    

    This will definitely create a $_POST["login"] and thus the following line won't fail:

    if(isset($_POST['login']))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题