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

PHP-使用登录系统保护仅会员页面,第1张

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

我建议您改变方法。

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

首先,将db connect / login内容移到一个单独的文件中,

require
include
将该文件移到每个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://pre.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. -->


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5641118.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存