A PHP session generated by the session_start()
function automatically creates a random session cookie for the current session. We can actually access this cookie by getting the string contained within the document.cookie
property. Using jQuery this task is pretty easy.
A PHP session starts just like this:
<?php session_start(); ?>
The session cookie is immediately accessible:
$(function() { console.log(document.cookie); // PHPSESSID=4b668f94a97ca6742adbf4ab74edd6ad });
We can get the token value pretty easily:
(function($) { $.getPHPSessionCookie = function() { var token = document.cookie.replace(/phpsessid=/gi, ''); return token; }; })(jQuery); $(function() { console.log($.getPHPSessionCookie()); // 4b668f94a97ca6742adbf4ab74edd6ad });
This token could be easily used during AJAX requests as a further validation of session data, though all PHP developers use an additional encrypted token in the $_SESSION
superglobal array to add an extra layer of protection. This means that this basic token should never be trusted.