小编典典

PHP-使用登录系统保护仅会员页面

html

您好 ,我为编写的PHP代码所困扰。我盯着这个看了好几个小时都没有成功,请帮忙找出我显然已经解决的所有错误。

我想要此脚本执行的操作是从html表单页面中查询数据库表(“用户”)以确保其密码和用户名正确,然后在单独的表(“令牌”)中插入随机令牌(我以前使用过的方法,它可以正常工作)进入“
tk”列,然后用户进行常规身份验证。代码从“用户”表拉入“令牌”表中的“ gauth”列。

进行其他常规身份验证的原因是,我可以提取其用户名并将其显示在我计划“保护”的所有页面上

对不起,如果我感到困惑,这是我可以改进的最佳方法。另外,我不太擅长格式化:)。稍后我将添加一些html,这就是标记在那里的原因。

MySQL表:

用户示例:

cols:        username  | password  |    email              | classcode | tcode   | genralauth |
             hello     | world     | hello.world@gmail.com | 374568536 | somthin | 8945784953 |

Tokens Example:

cols:          gauth   |      tk      |
            3946893485 |wr8ugj5ne24utb|

PHP:

<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);

if ($conn->query($sql1) === TRUE) {
    echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);

if ($conn->query($sql2) === TRUE) {
    echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
    $correct = TRUE;
}
else {
    $correct = FALSE;
}
?>
<?php
    if ($correct === TRUE) {
        $sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
        $result3 = $conn->query($sql3);
    }
?>
<?php
    if ($correct === TRUE) {
        $sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' ,       '".$result3."')";

        if ($conn->query($sql4) === TRUE) {
            echo "New token genrated.";
        } else {
            echo "Error: " . $conn->error;
        }
    }
?>
<?php
    if ($correct === TRUE) { ?>
    <p>Succesfuly loged in!</p><br/>
    <a href="../index.php<?php echo " ?view=teacher";?>"><button>Continue</button></a><br/>
<?php
}
elseif ($correct === FALSE) { ?>
    <p>Incorrect, please try again.</p><br/>
    <a href="../login.php"><button>Back</button></a><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;   
}
$conn->close();
?>

这是我将在大多数页面上用于令牌身份验证的PHP,但是它实际上并没有检查数据库的“令牌”,我还需要一种使用常规身份验证显示登录用户名的方法。

PHP:

<html>
<h1 class="title">Virtual Work Sheets!</h1> 
<a href="login.php"><p class="h_option">[Log In / Register]</p></a><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);

?>
<?php
if (!$_GET['tk'] == $data) {
    echo "
    <p>Invalid token, please consider re-logging.</p>
    ";
}
else {
?>
<?php
switch ($_GET['view']) {
    case teacher:
?>

教师页面html在这里…

<?php 
    break;
    case student:
?>

学生页面html在这里…

<?php
    break;
    default:
        echo "Please login to view this page.";
}
}?>
</html>

阅读 268

收藏
2020-05-10

共1个答案

小编典典

我建议您改变方法。

尽管乍看之下这些示例文件看起来很多,但是一旦研究它们,您会发现它实际上比现在的方向更加简单和合乎逻辑。

首先,将db connect / login内容移到一个单独的文件中,requireinclude将该文件移到每个PHP页面的顶部:

初始化PHP

    // Create connection
    $conn = new mysqli($servername, $username, $password, $db);

    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    //Might as well also load your functions page here, so they are always available
    require_once('fn/functions.php');
?>

现在,在“索引(和受限)”页面上查看我们如何使用它?

索引文件

<?php
    require_once('inc/head.inc.php');
    require_once('fn/init.php');
?>

<body>
    <!-- Examples need jQuery, so load that... -->
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <!-- and our own file we will create next... -->
    <script type="text/javascript" src="js/index.js"></script>

    <div id="pageWrap">
        <div id="loginDIV">
            LoginID: <input type="text" id="liID" /><br>
            LoginPW: <input type="password" id="liPW" /><br>
            <input type="button" id="myButt" value="Login" />
        </div>
    </div>

JS / INDEX.JS

$(function(){
    $('#myButt').click(function(){
        var id = $('#liID').val();
        var pw = $('#liPW').val();
        $.ajax({
            type: 'post',
             url: 'ajax/login.php',
            data: 'id=' +id+ '&pw=' +pw,
            success: function(d){
                if (d.length) alert(d);
                if (d==1) {
                    window.location.href = 'restricted_page.php';
                }else{
                    $('#liID').val('');
                    $('#liPW').val('');
                    alert('Please try logging in again');
                }
        }
        });
    });//END myButt.click

}); //END document.ready

AJAX /登录

<?php
    $id = $_POST['id'];
    $pw = $_POST['pw'];

    //Verify from database that ID and PW are okay
    //Note that you also should sanitize the data received from user

    if ( id and password authenticate ){
        //Use database lookups ot get this data: $un = `username`

        //Use PHP sessions to set global variable values
        $_SESSION['username'] = $un;
        echo 1;
    }else{
        echo 'FAIL';
    }

RESTRICTED_PAGE.PHP

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

    require_once('inc/head.inc.php');
    require_once('fn/init.php');
?>
<body>
    <h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
    <!--  AND here go all teh restricted things you need a login to do. -->
2020-05-10