15

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?

7 Answers 7

40

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>
Sign up to request clarification or add additional context in comments.

4 Comments

If $_SESSION['msg'] stores sensitive information, outputting to an unencrypted page is a security risk, and HTTPS should be used.
but by doing so you expose the value directly and it's accessible from the console and can be modified. What if you need to get a sensible information like a privilege_type id and you don't want your user to be able to change it : you need to access such value at runtime from a private methode and never store it to use it later.
If this gets cached then you'll see your world burn. That's why I prefer cookie method which is accepted answer.
Wow. There's a good answer and 2 good constructive points. My question based on this specific answer and these comments is, what if I just want to check if the user is in fact logged in? Just a quick true or false check returned in JSON as presented in this reply, regarding a successful login that has already happen in a different page written in PHP Only? Then it's OK?
21

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

7 Comments

Why is this being voted up? harto's solution proves it untrue.
Yes agreed, but it doesn't answer the question and is in fact presenting misleading information.
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.
Cookies are no more secure, they're easily visible in most browsers.
Right. Shouldn't have mentioned security. My point was that $_SESSION is not a client-side construct. Either stash the value in a client-side construct ($_COOKIE, render it out in the HTML), or make an AJAX request to a service that will return that value from your server-side session.
|
6

.. 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'].'"';

Comments

3

If this helps anyone, those examples returned null, so I just used:

<?php session_start();
   $msg = $_SESSION['msg'];
?>

<script>
   <?php echo "var msg = '" .$msg . "'"; ?>
</script>

3 Comments

Not really answering the question
I see you -1'd me. The question is "Is it possible to read $_SESSION['msg'] with Javascript?" my answer uses javascript to access a php variable, in case that helped anyone. Your comment is that my answer did not resolve the question. You are wrong.
Read your answer once again. The question was is it possible to read session variables. The answer is "No", but there's a workaround helpful in some situations. You didn't state that. Also some code formatting would be nice. var msg = '<?php echo $msg; ?>'; looks much better than joining the whole javascript line in php. I'm sorry, but this doesn't look like the answer to the question asked. Try improving it.
1
<script type="text/javascript">
var foo="<?php echo $_SESSION['user_id']; ?>";
alert(foo);
</script>

1 Comment

the alert message returns <?php echo $_SESSION['user_id']; ?>. Any ideas?
1

To make an even easier example of Luis Melgratti´s answer you can just return a json encoded value from PHP and use jQuery to parse it, like this:

Javascript:

$("#some_button")
    .click(function()
    {
        $.ajax(
        {
            url: "get_session.php",
            cache: false
        })
        .done(function(result)
        {
            var session_credentials = $.parseJSON(result);
            console.log(session_credentials);
        });
    });

PHP:

//get_session.php
<?php
    session_start();
    echo json_encode($_SESSION);
?>

I believe there are even more answers on a similar SO-thread here: how-to-access-php-session-variables-from-jquery-function-in-a-js-file

Comments

1

May It Works :

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie('PHPSESSID');

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.