Edgars Aivars Edgars Aivars - 3 months ago 11x
Javascript Question

authenticate via .htaccess on custom login

So my problem is this - i have custom authenticate code that writes in db `online` table ip, session id and user id(if login and password match) based on registered user data.
Soo i have some js scripts that are only needed when you are authenticated and i dont want them to be accessible if you are not logged in(its not unsecured but why to give playground), and i want all the script to be in one .js file.
Soo i thoght maybe i can make that folder with .htacces password protection and when i log into admin panel some php code make me also logged in in that appache system - is this possible? or i need to make js file php and then include it or something else? im baffled.


Sure you can do that! But there is a much simpler way. Just use a php file as your script tag's src attribute, and setup that file to handle the request:

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

The PHP file controls which Javascript is sent to the client. This is because PHP script can tell whether the user is logged in by looking at $_SESSION variables:


    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
        //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");

        //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');