PHP - 使用登录系统保护仅限会员的页面 [英] PHP - Secure member-only pages with a login system

查看:21
本文介绍了PHP - 使用登录系统保护仅限会员的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我被自己编写的 PHP 代码难住了.我已经盯着这个看了几个小时没有成功,请帮忙找出我显然已经解决的任何错误.

我想让这个脚本做的是从一个 html 表单页面,查询一个数据库表('users')以确保他们的密码和用户名是正确的,然后在一个单独的表('tokens')中插入一个随机令牌(我之前使用的方法,它有效)放入tk"列,以及用户的一般身份验证.代码从用户"表中提取到令牌"表中的gauth"列中.

额外的通用身份验证的原因是我可以提取他们的用户名并将其显示在我计划保护"的所有页面上

对不起,如果我感到困惑,这是我能改进的最好的方法.另外,我不太擅长格式化:).稍后我将添加一些 html,这就是标签存在的原因.

MySQL 表:

用户示例:

cols: 用户名 |密码 |电子邮件 |类代码 |代码 |将军 |你好 |世界|hello.world@gmail.com |374568536 |薄 |8945784953 |

令牌示例:

cols: gauth |传统知识 |3946893485 |wr8ugj5ne24utb|

PHP:

<?phpsession_start();错误报告(0);$servername = "本地主机";$用户名 = "-------";$password = "-------";$db = "vws";?><?php//创建连接$conn = new mysqli($servername, $username, $password, $db);//检查连接如果($conn->connect_error){die("连接失败:" . $conn->connect_error);}?><?php$sql1 = "从用户中选择用户名";$data1 = $conn->query($sql1);if ($conn->query($sql1) === TRUE) {回声";}?><?php$sql2 = "从'用户'中选择密码";$data2 = $conn->query($sql2);if ($conn->query($sql2) === TRUE) {回声";}?><?php$bytes = openssl_random_pseudo_bytes(3);$hex = bin2hex($bytes);?><?phpif($_POST['pss'] == $data2 和 $_POST['uname'] == $data1) {$正确=真;}别的 {$正确=假;}?><?php如果($正确 === TRUE){$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";$result3 = $conn->query($sql3);}?><?php如果($正确 === TRUE){$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";if ($conn->query($sql4) === TRUE) {echo "新令牌生成.";} 别的 {回声错误:".$conn->错误;}}?><?php如果 ($正确 === TRUE) { ?><p>登录成功!</p><br/><a href="../index.php<?php echo " ?view=teacher";?>"><button>继续</button></a><br/><?php}elseif ($correct === FALSE) { ?><p>不正确,请重试.</p><br/><a href="../login.php"><button>返回</button></a><br/><?php}?><?php如果($正确 === TRUE){$_SESSION['auth'] = $hex;$_SESSION['logstat'] = TRUE;}?><?php如果($正确 === FALSE){$_SESSION['logstat'] = FALSE;}$conn->close();?>

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

PHP:

<h1 class="title">虚拟工作表!</h1><a href="login.php"><p class="h_option">[登录/注册]</p></a><hr/><div class="body"><?phpsession_start();错误报告(0);$servername = "本地主机";$username = "root20";$password = "jjewett38";$db = "vws";?><?php//创建连接$conn = new mysqli($servername, $username, $password, $db);//检查连接如果($conn->connect_error){die("连接失败:" . $conn->connect_error);}?><?php$sql = "从令牌中选择 tk";$data = $conn->query($sql);?><?php如果 (!$_GET['tk'] == $data) {回声"<p>无效的令牌,请考虑重新登录.</p>";}别的 {?><?php开关($_GET['view']){案例老师:?>

教师页面 html 在这里...

学生页面 html 在这里...

解决方案

我建议你改变你的方法.

虽然乍一看这些示例文件看起来很多,但一旦你研究它们,你就会发现它比你现在的方向更简单和合乎逻辑.

首先,将数据库连接/登录内容移动到一个单独的文件中,并将该文件requireinclude 放在每个PHP 页面的顶部:

INIT.PHP

//创建连接$conn = new mysqli($servername, $username, $password, $db);//检查连接如果($conn->connect_error){die("连接失败:" . $conn->connect_error);}//也可以在这里加载您的功能页面,以便它们始终可用require_once('fn/functions.php');?>

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

INDEX.PHP

<身体><!-- 示例需要 jQuery,所以加载它...--><script src="https://code.jquery.com/jquery-1.11.3.js"></script><!-- 以及我们接下来将创建的我们自己的文件...--><script type="text/javascript" src="js/index.js"></script><div id="pageWrap"><div id="登录DIV">登录ID:<input type="text" id="liID"/><br>登录密码:<input type="password" id="liPW"/><br><input type="button" id="myButt" value="登录"/>

JS/INDEX.JS

$(function(){$('#myButt').click(function(){var id = $('#liID').val();var pw = $('#liPW').val();$.ajax({类型:'帖子',url: 'ajax/login.php',数据:'id=' +id+ '&pw=' +pw,成功:功能(d){如果(d.length)警报(d);如果 (d==1) {window.location.href = 'restricted_pa​​ge.php';}别的{$('#liID').val('');$('#liPW').val('');alert('请重新登录');}}});});//结束myButt.click});//END document.ready

AJAX/LOGIN.PHP

RESTRICTED_PAGE.PHP

<身体><h1>欢迎来到管理页面,<?php echo $_SESSION['username'];?><!-- 在这里,您需要登录才能完成所有受限制的事情.-->

<小时>

更多关于 AJAX - 研究简单的例子

Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.

What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.

The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"

Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.

MySQL Tables:

Users Example:

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();
?>

This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.

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

Teacher page html here...

<?php 
    break;
    case student:
?>

Student page html here...

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

解决方案

I suggest that you change your approach.

Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.

First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:

INIT.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');
?>

Now, see how we use it on the Index (and Restricted) pages?

INDEX.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/LOGIN.PHP

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


More about AJAX - study the simple examples

这篇关于PHP - 使用登录系统保护仅限会员的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆