PHP - 安全仅供会员的页面与一个登录系统 [英] PHP - Secure member-only pages with a login system

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

问题描述

您好,我已经由PHP code我写难住了。我在这盯着几个小时没有成功,请大家帮忙找我显然超过了任何错误。

我要的这个脚本做的是从一个HTML表单页面,查询数据库表(用户),以确保他们的用户名和密码是正确的,那么在一个单独的表('令牌')插入随机令牌(我以前使用的方法,它的工作原理)进入TK列,用户一般权威性。 code,从用户表拉入gauth'柱,在令牌表。

究其原因,更多的普通AUTH是这样我就可以拉他们的用户名和所有我计划在保护

页显示它

很抱歉,如果我是混乱的,这是我可以完善它最好的。另外,我不是那种善于格式:)。我会在以后添加一些HTML,这就是为什么标签的存在。

MySQL表:

用户实例:

  COLS:用户名|密码|电子邮件|类code | T $ C $ B | genralauth |
             你好|世界| hello.world@gmail.com | 374568536 | somthin | 8945784953 |

令牌示例:

  COLS:gauth | TK |
            3946893485 | wr8ugj5ne24utb |

PHP:

 < HTML和GT;
< PHP
在session_start();
(0)使用error_reporting;
$服务器名=localhost的;
$用户名=-------
$密码=-------
$ DB =VWS;
?>
< PHP
//创建连接
康涅狄格州$ =新的mysqli($服务器名,用户名$,$密码,$分贝);//检查连接
如果($ conn-> connect_error){
死(连接失败:$ conn-> connect_error);
}
?>
< PHP
$ SQL1 =选择用户名来自用户的;
$数据1 = $ conn->查询($ SQL1);如果($ conn->查询($ SQL1)===真){
    回声;
}
?>
< PHP
$ SQL2 =选择密码从'用户';
$ DATA2 = $ conn->查询($ SQL2);如果($ conn->查询($ SQL2)===真){
    回声;
}
?>
< PHP
$字节= openssl_random_pseudo_bytes(3);
$十六进制= BIN2HEX($字节);
?>
< PHP
如果($ _ POST ['PSS'] == $数据2和$ _ POST ['的uname'] == $数据1){
    $正确= TRUE;
}
其他{
    $正确= FALSE;
}
?>
< PHP
    如果($正确=== TRUE){
        $ SQL3 =SELECT generalauth用户的其中password ='​​[PSS']。'$ _ POST。';
        $ result3 = $ conn->查询($ SQL3);
    }
?>
< PHP
    如果($正确=== TRUE){
        $ sql4 =INSERT INTO令牌(TK,gauth)VALUES($十六进制,$ result3'。)        如果($ conn->查询($ sql4)===真){
            回声新令牌genrated。
        }其他{
            回声错误:。 $ conn->错误;
        }
    }
?>
< PHP
    如果($正确=== TRUE){&GT?;
    &所述p为H.; Succesfuly loged上述<!/ P>&所述峰; br />
    < A HREF =../的index.php<?PHP的回声视图=老师吗?;?>><按钮>继续< /按钮>< / A>< BR />
< PHP
}
ELSEIF($正确=== FALSE){&GT?;
    < P>错误,请重试< / P>< BR />
    LT&; A HREF =../的login.php><按钮和GT;返回< /按钮>< / A>< BR />
< PHP
}
?>
< PHP
如果($正确=== TRUE){
$ _SESSION ['权威性'] = $(十六进制);
$ _SESSION ['logstat'] = TRUE;
}
?>
< PHP
如果($正确=== FALSE){
$ _SESSION ['logstat'] = FALSE;
}
$ conn->关闭();
?>

这是我要对令牌身份验证大多数页面使用,howver它实际上不到风度检查数据库'令牌'PHP的,我也需要用户显示的用户名签约使用一般的身份验证的一种方式。

PHP:

 < HTML和GT;
< H1类=标题>虚功材<!/ H1>
< A HREF =login.php中>&LT,P类=h_option> [登录/注册] LT; / P>< / A><小时/>
< D​​IV CLASS =身体>
< PHP
在session_start();
(0)使用error_reporting;
$服务器名=localhost的;
$用户名=root20;
$密码=jjewett38;
$ DB =VWS;
?>
< PHP
//创建连接
康涅狄格州$ =新的mysqli($服务器名,用户名$,$密码,$分贝);//检查连接
如果($ conn-> connect_error){
死(连接失败:$ conn-> connect_error);
}
?>
< PHP
$的SQL =SELECT FROM TK令牌;
$数据= $ conn->查询($的SQL);?>
< PHP
如果(!$ _ GET ['TK'] == $的数据){
    回声
    < P>令牌无效,请考虑重新记录< / P>
    
}
其他{
?>
< PHP
开关($ _GET [视图]){
    案例老师:
?>

教师HTML页面在这里...

 < PHP
    打破;
    学生情况:
?>

学生HTML页面在这里...

 < PHP
    打破;
    默认:
        回声请登录后查看此页。
}
?}>
< / HTML>


解决方案

我建议你改变你的方法。

虽然乍看之下这些示例文件,貌似很多,一旦你学习他们,你会发现它真的更简单,符合逻辑的做法比你现在前进的方向。

首先,将DB连接/登录的东西到一个单独的文件和要求包含该文件在每个PHP页面顶部:

的init.php
    

  //创建连接
    康涅狄格州$ =新的mysqli($服务器名,用户名$,$密码,$分贝);    //检查连接
    如果($ conn-> connect_error){
    死(连接失败:$ conn-> connect_error);
    }    //不妨也在这里加载功能页面,因此它们总是可用
    require_once('FN /的functions.php');
?>

现在,看看我们如何使用它的指数(和限制)的页面?

的index.php

 < PHP
    require_once('INC / head.inc.php');
    require_once('FN /的init.php');
?><身体GT;
    <! - 例如jQuery的需要,因此加载... - >
    <脚本SRC =HTTPS://$c$c.jquery.com/jquery-1.11.3.js>< / SCRIPT>
    <! - 和我们自己的文件,我们会在下一个创造... ... - >
    <脚本类型=文/ JavaScript的SRC =JS / index.js>< / SCRIPT>    < D​​IV ID =pageWrap>
        < D​​IV ID =loginDIV>
            为LoginID:LT;输入类型=文本ID =liID/>< BR>
            LoginPW:LT;输入类型=密码ID =liPW/>< BR>
            <输入类型=按钮ID =myButtVALUE =登录/>
        < / DIV>
    < / DIV>

JS / INDEX.JS

  $(函数(){
    $('#myButt')。点击(函数(){
        。VAR ID = $('#liID)VAL();
        VAR PW = $('#liPW)VAL()。
        $阿贾克斯({
            类型:'后',
             网址:'AJAX / login.php中',
            数据:'ID ='+ ID +'和; PW ='+ PW,
            成功:函数(D){
                如果(d.length)报警(D);
                如果(D == 1){
                    window.location.href ='restricted_pa​​ge.php';
                }其他{
                    $('#liID)VAL('')。
                    $('#liPW)VAL('')。
                    警报(请再次尝试登录');
                }
        }
        });
    }); // END myButt.click}); // END的document.ready

AJAX / login.php中

 < PHP
    $ n = $ _ POST ['身份证'];
    $ PW = $ _ POST ['私服'];    从数据库//验证ID和PW都还好
    //请注意,您还应该从消毒用户接收到的数据    如果(ID和密码进行验证){
        //使用数据库查找OT得到这样的数据:$ UN =`username`        //使用PHP会话设置全局变量值
        $ _SESSION [用户名] = $取消;
        回音1;
    }其他{
        呼应「不及格」;
    }

RESTRICTED_PAGE.PHP

 < PHP
    如果(!使用isset($ _ SESSION ['用户名'])){
        标题(位置:.'index.php');
    }    require_once('INC / head.inc.php');
    require_once('FN /的init.php');
?>
<身体GT;
    < H1>欢迎管理页面,< PHP的echo $ _SESSION [用户名]; ?>
    <! - 在这里全力以赴格兰限制的东西,你需要登录的事情。 - >


更多关于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天全站免登陆