在自定义登录时通过.htaccess进行身份验证

时间:2016-07-22 22:48:43

标签: javascript php .htaccess

所以我的问题是这个 - 我有自定义验证代码,它根据注册的用户数据写入db`online`表ip,会话ID和用户ID(如果登录和密码匹配)。
所以我有一些js脚本只有在你经过身份验证时才需要,如果你没有登录我不希望它们可以访问(它不是没有安全但为什么要给游乐场),我想要所有的脚本来在一个.js文件中。左,所以我可以用.htacces密码保护制作该文件夹,当我登录管理面板时,一些PHP代码让我也登录到该appache系统 - 这可能吗?或者我需要制作js文件php然后包含它或其他东西?我很困惑。

1 个答案:

答案 0 :(得分:1)

当然可以这样做!但是有一种更简单的方法。只需使用php文件作为脚本标记的src属性,并设置该文件来处理请求:

<script src="/path/to/js_handler.php"></script>

PHP文件控制将Javascript发送到客户端。这是因为PHP脚本可以通过查看$_SESSION变量来判断用户是否已登录:

<强> js_handler.php

<?php
    if(session_status()=== PHP_SESSION_NONE) session_start();
    $loggedIn = false;

    //determine whether the user is logged in by looking at values set
    // in $_SESSION by the login script. This is just an example
    if(isset($_SESSION['user']) && $_SESSION['expires'] > time()) 
        $loggedIn = true;

    //set JS header (otherwise the browser will expect an HTML file)
    header('Content-Type: application/javascript');

    //now send the right file to the browser
    if($loggedIn){
        //instruct the browser and proxies to never cache this file. Probably
        //better just set short caching (1-2hrs) to reduce server load
        header("Cache-Control: no-cache, no-store, must-revalidate");
        header("Expires: 0");

        readfile('/path/to/private.js');
    }
    else{
        //allow caching and reusing for up to 7 days
        header("Cache-Control: max-age=" . 60*60*24*7); //max age allowed: 7 days
        header("Expires: ".gmdate('D, d M Y H:i:s', time() + 60*60*24*7).' GMT');

        readfile('/path/to/public.js');
    }