0

I have set a session in PHP, which is creating a cookie: PHPSESSID... I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.

In PHP I am setting the sessions like:

session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();

I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?

At the moment I am just using:

document.cookie.indexOf( 'PHPSESSID' )

which seems like a bit of a botch.

2 Answers 2

1

The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.

You could parse the cookies with the following function (not tested):

function getCookieValue(name)
{
    // find cookie entry in middle?
    var s=document.cookie,
        c=s.indexOf("; "+name+"=");

    if(c==-1)
    {
        // no, is it at the start?
        c=s.indexOf(name+"=");
        if(c!=0) return null;
    }

    // get length of value
    var l=c+name.length+1,
        e=s.indexOf(";",l);

    // is it at the end?
    if(e==-1) e-s.length;

    // cut out the value
    return s.substring(l,e);
}

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

1

Use this Jquery plugin, it's so cool.

https://github.com/carhartl/jquery-cookie

You can use it like this way:

if($.cookie('PHPSESSID') != undefined){
 //PHPSESSID exists
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.