Search code examples
javascriptphpsessioncookiessession-cookies

Access the PHP session name in Javascript


I'm currently using this to check if a cookie name exist in the browser:

document.cookie.indexOf('myCookie=')

This works if the cookie was set via PHP's setcookie() but this doesn't appear to work on PHP sessions.

E.g. if the "cookie" was set through session_start();, you can see in the browser inspector the cookie name with an expiration of "Session". I can't seem to access that session cookie name via JS. Any ideas?

To be clear: I need to check if the PHP session cookie name is present in the browser, not the session data.


Solution

  • It is possible to set the PHP session cookie to be available only via HTTP (i.e. not in JS) if your session.cookie_httponly PHP configuration setting is enabled. In other words, you need to disable it / set it to false for your session cookie to be accessible in JS.

    You can check its value like so:

    <?php
    var_dump(ini_get('session.cookie_httponly'));
    

    Generally, this setting is enabled for security reasons, so I would highly suggest questioning the necessity of doing this.