views:

2994

answers:

3

Is it possible to read a session value with Javascript?

For example, if I assigned a value into a session in PHP:

$_SESSION['msg'] = "ABC Message";

Is it possible to read $_SESSION['msg'] with Javascript?

+4  A: 

$_SESSION is a server-side construct. You would need to store that variable in $_COOKIE to be able to access it client-side.

Will Green
Why is this being voted up? harto's solution proves it untrue.
da5id
Because the first part of the answer is quite correct.
Kalium
Yes agreed, but it doesn't answer the question and is in fact presenting misleading information.
da5id
How is this misleading? You cannot read a session variable with javascript. You either have to stuff the value into a cookie, which javascript could access, or have it rendered out to the page itself. That is not very secure.
Will Green
+1  A: 

.. Or you can use ajax to retrive your server side session value into you client-side javascript.` (quick, dirty and untested example, using jQuery)

Javascript Side:

$.ajax({
      url: "test.php",
      cache: false,
      success: function(html){
        eval( html ); /// UGLY NASTY YOU MUST VALIDATE YOUR INPUTS... JUST AN EXAMPLE
      }
    });

PHP side test.php:

echo 'var myData = "'. $_SESSION['msg'].'"';
Luis Melgratti
+2  A: 

A very simple way is to generate the JavaScript with some PHP code:

<script type="text/javascript">
    <?php echo 'var msg = "'.json_encode($_SESSION['msg']).'";';
</script>
harto
If $_SESSION['msg'] stores sensitive information, outputting to an unencrypted page is a security risk, and HTTPS should be used.
Jeff Ober
you could use json_encode() to properly escape it
Tom Haigh
@tomhaigh Thanks, updated accordingly
harto