栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/635248.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号