I created session in CakePHP like this:
$User = array('userid'=>232, 'access'=>1)
$this->Session->write('User',$User);
Now I want to check userid
in session using JavaScript / jQuery
Is there any direct method to access this session in JavaScript.
Thanks
I created session in CakePHP like this:
$User = array('userid'=>232, 'access'=>1)
$this->Session->write('User',$User);
Now I want to check userid
in session using JavaScript / jQuery
Is there any direct method to access this session in JavaScript.
Thanks
Share Improve this question asked May 16, 2012 at 12:23 AwanAwan 18.6k38 gold badges93 silver badges133 bronze badges3 Answers
Reset to default 16Is there any direct method access this session in JavaScript directly.
No. Session data is stored on the server.
In order to access it, you need to expose it on a URI via PHP, and then make an HTTP request to that URI (possibly using Ajax).
// js function
var getUserId = function()
{ userId = null;
$.ajax({
type: "POST",
url: "ajax.php", // @TODO set the right Path
async : false,
success: function(msg)
{
userId = msg;
}
});
return userId;
}
/*PHP ajax.php*/
<?php
echo $this->Session->get('User'); or $_SESSION['User']
?>
--- CAll----------
var userId = getUserId();
Why would you check a userid on the client, where it can be faked, manipulted, etc? Just use the session ID.
Apart from that, there are two easy and additional ways to expose the user id to JavaScript. Both have the advantage that no additional AJAX call is needed (making your page more responsive):
- Store the user id in a cookie.
- Generate a JavaScript variable that stores the user id:
In your php file, do the following:
<script>
var userId = <?php echo $User['userid']; ?>;
</script>
This is just an example for one value. A better way for exposing PHP variables to JavaScript would be a separate PHP file/controller action like this:
<?php
session_start();
$myValues = array();
$myValues['User'] = get_user_from_session(); // just an example
// Assemble all your values here
header('Content-type: application/json');
echo "var myValues = ".json_encode($myValues);
// or, if you go for a JSONP style init, use
// echo "initValues(".json_encode($myValues).")";
You can then include the values with the src attribute of the script. This however will cause another HTTP request.