电子商务网站身份验证级别,以便访问网站的安全区域

时间:2021-03-09 11:28:24

标签: php mysql sql

晚上好

我正在开发一个电子商务网站,该网站的一些必需功能是不同级别的身份验证,例如只有管理员可以访问管理区域,用户可以访问所有其他页面,而残疾人则可以基本要重新注册。

当我尝试登录时,它可以工作,但似乎只有 $_SESSION['user'] 正在工作,而其他两个会话没有工作。

这是验证码:

<?php
    //start session management
    session_start();
    //connect to the database
    require('connection.php');
    //retrieve the functions
    require('../model/functions_members.php');
   
   
    //retrieve the username and password entered into the form
    $username = $_POST['username'];
    $password = $_POST['password']; 
    $stmt = $conn->query("SELECT LAST_INSERT_ID()");
    $lastId = $stmt->fetchColumn();
    $userID = $lastId;

    //call the retrieve_salt() function
    $result = retrieve_salt($username);
        
    //retrieve the random salt from the database
    $salt = $result['salt'];
    //generate the hashed password with the salt value
    $password = hash('sha256', $password.$salt); 
        
    //call the login() function
    $count = login($username, $password);

    //query the database
    $sql = "SELECT userType FROM sport_cars.user WHERE userID = '.$userID.'";
    //prepared statement
    $statement = $conn->prepare($sql);
    $statement->execute();
    $result = $statement->fetchAll();
    $statement->closeCursor();
    foreach ($result as $row) :
        $userType = $row['userType'];    
    endforeach;

        
     //if there is one matching record
     if($count == 1 && $userType = 'User')
     { 
         //start the user session to allow authorised access to secured web pages
         $_SESSION['user'] = $user;
         //if login is successful, create a success message to display on the products page
         $_SESSION['success'] = 'Hello ' . $username . '. Have a great day!';
         //redirect to products.php
         header('location:../index.php');
     }
     elseif($count == 1 && $userType = 'Admin')
     {
           //start the admin session to allow authorised access to secured web pages
           $_SESSION['admin'] = $admin;
           //if login is successful, create a success message to display on the products page
           $_SESSION['success'] = 'Hello ' . $username . '. Have a good day!';
           //redirect to products.php
           header('location:../index.php');
     }
     elseif($count == 1 && $userType = 'Disabled')
     {
        
              //start the disabled session to allow authorised access to secured web pages
         $_SESSION['disabled'] = $disabled;
         //if login is successful, create a success message to display on the products page
         $_SESSION['success'] = 'Hello ' . $username . '. Have a great day!';
         //redirect to products.php
         header('location:../index.php');
        
     }
     else 
     {
         //if login not successful, create an error message to display on the login page
         $_SESSION['error'] = 'Incorrect username or password. Please try again.';
         //redirect to login.php
         header('location:../members.php');
     }

 ?>

这是管理页面:

<?php
            //start session management
            session_start(); 
            //connect to the database
            require_once("controller/connection.php");
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?php
            require_once("controller/connection.php");

            if( isset($_SESSION['admin'])) { 
                // grant access
              } else { 
                //redirect 
                header('location:members.php');
              }
        ?>
        <title>Sport Cars | Home</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
        <link href="view/style.css" rel="stylesheet">
        <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
        <script src="view/js/jquery-3.5.1.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script>
    </head>
    <body>
        <header>
            <h1>Sport Cars</h1>
        </header>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <a class="navbar-brand" href="index.php" accesskey="1">Sports Cars</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavDropdown">
                <ul class="navbar-nav" >
                    <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="members.php" accesskey="2">Members</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link" href="admin.php" accesskey="3">Admin Area</a>
                    </li>
                    <li class="nav-item">
                    <a class="nav-link" href="cart.php" accesskey="4">Cart</a>
                    </li>
                    <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="cars_cat.php" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false" accesskey="5">
                    Car categories
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                    <?php
                        //query the database
                        $sql = "SELECT * FROM sport_cars.category";
                        //prepared statement
                        $statement = $conn->prepare($sql);
                        $statement->execute();
                        $result = $statement->fetchAll();
                        $statement->closeCursor();
                        //display the category names in a hyperlink
                        foreach($result as $row):
                            echo "<li><a href = 'category.php?categoryID=" . $row['categoryID'] . "'>".$row['categoryName']."</a>  </li>";
                        endforeach;
                     ?>
                    </ul>
                    </li>
                </ul>
                </div>
            </div>
        </nav>
        <br>
        <div class="typed-area">
            <h2><span class="animate"> Welcome to the Admin Area</span></h2>
            <span style="visibility:hidden;">|</span>
        </div>
        <br>
        <section>
            <div id="cars">
            <button type="button" class="btn btn-primary" onclick="location.href='add_car.php'">Add a new car</button>
            <br>
            <br>
            <?php   
                //query the database
                $sql = "SELECT * FROM sport_cars.cars";
                //prepared statement
                $statement = $conn->prepare($sql);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                //display the result for each row using a foreach loop           
                foreach($result as $row):
                    $carID = $row['carID'];
                    $carName = $row['carName'];
                    $carDescription = $row['carDescription'];
                    $carPrice = $row['carPrice'];
                    $Photo = $row['Photo'];
                    echo "<div><p><img id='cars' width= 40% height= auto alt='Car Photo' src=".'view/images/'. $row['Photo'] . "></p>";
                    echo "<p><b>" . $row['carName'] . "</b></p>";
                    echo "<p>" . $row['carDescription'] . "</p>";
                // Use the number format function to format the price displayed to two decimal places
                    echo "<p>" . number_format($row['carPrice'], 2)   . "</p>";
                    echo "<p><a href='update_car.php?carID=$carID&carName=$carName&carDescription=$carDescription&carPrice=$carPrice&Photo=$Photo'> Update</a><span> | </span><a href='controller/car_delete_process.php?carID=$carID'>Delete</a></p></div>";
                endforeach;
            ?>
            </div>
            <aside id="categories">
            <h2 id="platforms">Car types</h2>
            <?php
                //query the database
                $sql = "SELECT * FROM sport_cars.category";
                //prepared statement
                $statement = $conn->prepare($sql);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                //display the category names in a hyperlink
                foreach($result as $row):
                    echo "<p><a href = 'category.php?categoryID=" . $row['categoryID'] . "'>".$row['categoryName']."</a>  </p>";
                endforeach;
           ?>
        </aside>
           
        </section>
        <div ><p id="log_out">Do you need to <a href="destroy.php">Log out ?</a></p></div>
        <footer id="footer">
                    <h3>Contact Us</h3>
                    <p><i class="fas fa-at"></i> sportsCars@gmail.com</p>
                    <p><i class="fas fa-mobile"></i> +61 123 333 548</p>
                    <p><i class="fas fa-compass"></i> <strong>Sydney</strong> , Australia</p>
        </footer>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
        <script src="view/js/typed.js"></script>
        <script>
            var typed = new Typed('.animate', {
                strings: [
                    "Welcome to the Admin Area",
                    "Here, you will have control of your Cars",
                    "Enjoy!"
                    ],
                    typeSpeed: 50,
                    backSpeed: 50,
                    loop: true

            });
        </script>
    </body>
</html>

认证功能:

<?php

//create a function to retrieve salt

function retrieve_salt($username)
{
    global $conn;
    $sql = "SELECT * FROM games_hub.user WHERE username = :username";
    $statement = $conn->prepare($sql);
    $statement->bindValue(':username', $username);
    $statement->execute();
    $result = $statement->fetch();
    $statement->closeCursor();
    return $result;
}

//create a function to login
function login($username, $password)
{
    global $conn;
    $sql = "SELECT * FROM games_hub.user WHERE username = :username AND password = :password ";
    $statement = $conn->prepare($sql);
    $statement->bindValue(':username', $username);
    $statement->bindValue(':password', $password);
    $statement->execute();
    $result = $statement->fetchAll();
    $statement->closeCursor();
    $count = $statement->rowCount();    
    return $count;
}
?>

<!-- create a function to add a new user -->
<?php
function add_user($username, $password, $salt, $first_name, $last_name, $email)
{
    global $conn;
    $sql = "INSERT INTO games_hub.user (username, password, salt, first_name, last_name, email) VALUES (:username, :password, :salt, :first_name, :last_name, :email)";
    $statement = $conn->prepare($sql);
    $statement->bindValue(':username', $username);
    $statement->bindValue(':password', $password);
    $statement->bindValue(':salt', $salt);
    $statement->bindValue(':first_name', $first_name);
    $statement->bindValue(':last_name', $last_name);
    $statement->bindValue(':email', $email);
    $result = $statement->execute();
    $statement->closeCursor();
    return $result;  
    
    }
?> 

数据库:

-- Database: `sport_cars`
--

-- --------------------------------------------------------

--
-- Table structure for table `cars`
--

CREATE TABLE `cars` (
  `carID` int(4) NOT NULL,
  `carName` varchar(25) NOT NULL,
  `carDescription` text NOT NULL,
  `carPrice` decimal(8,2) NOT NULL,
  `categoryID` int(4) NOT NULL,
  `sold` tinyint(1) DEFAULT NULL,
  `Photo` varchar(100) NOT NULL,
  `quantity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `cars`
--

INSERT INTO `cars` (`carID`, `carName`, `carDescription`, `carPrice`, `categoryID`, `sold`, `Photo`, `quantity`) VALUES
(1, 'Lamber Fast', '                                                                        Very fast car                                                            ', '50000.00', 1, 0, 'andrew-pons-Os7C4iw2rDc-unsplash.jpg', 5),
(2, 'Buggy', 'Agile and easy to park', '10000.00', 2, 0, 'campbell-3ZUsNJhi_Ik-unsplash.jpg', 5),
(3, 'Royal Cargo', 'A real luxury for VIP', '99999.99', 3, 0, 'grahame-jenkins-p7tai9P7H-s-unsplash.jpg', 5),
(4, 'Speedy Zip', 'Sporty and modern', '70000.00', 1, 0, 'hakon-sataoen-qyfco1nfMtg-unsplash.jpg', 5),
(5, 'Betty Wagon', 'A van, ideal for long trips, on special!', '15000.00', 2, 0, 'john-vicente-CMzmQNU-DGE-unsplash.jpg', 5),
(6, 'Presidential ride', 'Premium Leather interiors and bulletproof frame', '99999.99', 3, 0, 'joshua-koblin-eqW1MPinEV4-unsplash.jpg', 5),
(7, 'Lambo Murcie', 'A rocket with wheels', '99999.99', 1, 0, 'karl-kohler-Hf1rAKkfMAg-unsplash.jpg', 5),
(8, 'Tombota Bamby', 'Reliable and smooth to drive', '15000.00', 2, 0, 'marcus-p-oUBjd22gF6w-unsplash.jpg', 5),
(9, 'Chrismer Vegas', 'A real luxury to have', '99999.99', 3, 0, 'peter-broomfield-m3m-lnR90uM-unsplash.jpg', 5),
(10, 'Lombus Belize', 'Ideal for car racing', '99999.99', 1, 0, 'sgcdesignco-81Dfucag9OY-unsplash.jpg', 5),
(11, 'Mistumbashi Areol', 'Perfect for small families, on special', '9000.00', 2, 0, 'sid-ramirez-tjLa5hbq6rw-unsplash.jpg', 5),
(12, 'Aubi b52', 'Low profile sport car', '80000.00', 1, 0, 'spencer-davis-iwFp5FvAUYE-unsplash.jpg', 5),
(13, 'Mabda f82', 'SUV on sale', '13000.00', 2, 0, 'viktor-theo-aIDkOU7eGgo-unsplash.jpg', 5),
(14, 'Balmoral Lux', 'Great for long travels', '99999.99', 3, 0, 'viktor-theo-xD3_PDKB54Y-unsplash.jpg', 5),
(15, 'Volbo b2', 'Smooth and easy to drive', '14000.00', 2, 0, 'pawel-kozak-kCB97plbcEg-unsplash.jpg', 5),
(16, 'lancia gamma', '                        \r\ndesigned for long journeys', '15000.00', 2, NULL, 'peter-broomfield-m3m-lnR90uM-unsplash.jpg', 5);

-- --------------------------------------------------------

--
-- Table structure for table `category`
--

CREATE TABLE `category` (
  `categoryID` int(4) NOT NULL,
  `categoryName` varchar(25) NOT NULL,
  `categoryDescription` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `category`
--

INSERT INTO `category` (`categoryID`, `categoryName`, `categoryDescription`) VALUES
(1, 'Sport', 'Fast and reliable'),
(2, 'Specials', 'The cars on special'),
(3, 'Luxury', 'High range cars with premium features');

-- --------------------------------------------------------

--
-- Table structure for table `sold_cars`
--

CREATE TABLE `sold_cars` (
  `carID` int(4) DEFAULT NULL,
  `userID` int(4) DEFAULT NULL,
  `date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `userID` int(4) NOT NULL,
  `first_name` varchar(64) NOT NULL,
  `last_name` varchar(64) NOT NULL,
  `Email` varchar(64) NOT NULL,
  `username` varchar(64) NOT NULL,
  `salt` char(64) NOT NULL,
  `password` char(64) NOT NULL,
  `userType` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`userID`, `first_name`, `last_name`, `Email`, `username`, `salt`, `password`, `userType`) VALUES
(2, 'John', 'Red', 'user@gmail.com', 'User', 'b846b99eee5b3e7ca5b8881c226e8175', '7693e0fa45e46284a4e86729ce7704cf96a4d849d4c8b0474ae6928280efe31f', 'User'),
(3, 'Mark', 'Green', 'red@gmail.com', 'Mark', '7398c00cec247cd2329685df2bc75b6e', '12cd4b5ac31cff49bdb2ae985daad0f74f4be4520edc39ae2bd5bd922c2e3978', 'Disabled'),
(14, 'Jim', 'Green', 'green@gmail.com', 'Jim', 'd9505b13b85312b1c5ca7b2efedea566', '1a8eae3937057d35d796657e971006e548b691cc561b256ee03f6fc86af03847', 'Admin');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `cars`
--
ALTER TABLE `cars`
  ADD PRIMARY KEY (`carID`),
  ADD KEY `categoryID` (`categoryID`);

--
-- Indexes for table `category`
--
ALTER TABLE `category`
  ADD PRIMARY KEY (`categoryID`);

--
-- Indexes for table `sold_cars`
--
ALTER TABLE `sold_cars`
  ADD KEY `carID` (`carID`),
  ADD KEY `userID` (`userID`);

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`userID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `cars`
--
ALTER TABLE `cars`
  MODIFY `carID` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55;

--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
  MODIFY `categoryID` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `userID` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `cars`
--
ALTER TABLE `cars`
  ADD CONSTRAINT `cars_ibfk_1` FOREIGN KEY (`categoryID`) REFERENCES `category` (`categoryID`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `sold_cars`
--
ALTER TABLE `sold_cars`
  ADD CONSTRAINT `sold_cars_ibfk_1` FOREIGN KEY (`carID`) REFERENCES `cars` (`carID`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `sold_cars_ibfk_2` FOREIGN KEY (`userID`) REFERENCES `user` (`userID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

我不确定这是否可能是身份验证问题,我不确定问题可能出在哪里,您认为这里有什么问题?

非常感谢您的帮助。 谢谢

0 个答案:

没有答案