Cookie Authentication: Restrict Access to Page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sonik son
    New Member
    • Aug 2005
    • 1

    Cookie Authentication: Restrict Access to Page

    Have a family website which requires username and password to access. I have the code to set a cookie ("user") upon successfull login.

    However, I cannot figure out how to allow access to the site by checking to see if the "user" cookie has been previously set (i.e. they have logged in before and are authorized to enter the site.)

    Currently using session variables to restrict access to page, but if anyone can provide code to check for "user" cookie, and allow/deny access based on that cookie, I would be most grateful.

    Thanks in advance.
  • bdbeames
    New Member
    • Jun 2007
    • 27

    #2
    if you are using javascript to set the cookie it should be easy to get it back.

    Here is a way with javascript
    these are my functions
    [code=javascript]
    function setCookie(cooki eName, value, expiredays)
    {
    var ExpireDate = new Date();
    ExpireDate.setT ime(ExpireDate. getTime() + (expiredays*24* 3600*1000));

    document.cookie = cookieName + "=" + escape(value) + ((expiredays == -1) ? "" : "; expires=" +
    ExpireDate.toGM TString()) + ";path=/";
    }
    function deleteCookie(na me)
    {
    setCookie(name, "",-1);
    }
    function getCookie(cooki eName)
    {
    if(document.coo kie.length > 0)
    {
    begin = document.cookie .indexOf(cookie Name+"=");

    if(begin != -1)
    {
    begin += cookieName.leng th+1;
    end = document.cookie .indexOf(";", begin);
    if( end == -1 ) end = document.cookie .length;
    return unescape(docume nt.cookie.subst ring(begin, end));
    }
    }
    return null;
    }
    [/code]

    now write function to set a cookie each time they login
    something like

    function letssetacookie( ) {
    deletecookie("c ookienamehere") ;
    setCookie("cook ienamehere", "thevaluehe re", numberofdaysher e);
    }

    now if you want to check the cookie when they come to the site do it on the pageload something like this

    onload="checkth ecookie()"

    function checkthecookie( ) {
    var isthereacookie = getCookie("cook ieName");

    if(isthereacook ie) {
    here write the code to display the login because there is not cookie
    } else {
    here write the code to log them in because there is a cookie
    this can be done with a fag or something indicating to your html
    that they can be logged in
    }
    }

    hope this helps

    Comment

    Working...