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?

John Rasch
  • 62,489
  • 19
  • 106
  • 139
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

7 Answers7

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>
harto
  • 89,823
  • 9
  • 47
  • 61
  • If $_SESSION['msg'] stores sensitive information, outputting to an unencrypted page is a security risk, and HTTPS should be used. – Jeff Ober Apr 16 '09 at 12:16
  • 2
    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. – svassr Oct 22 '12 at 20:22
  • 2
    If this gets cached then you'll see your world burn. That's why I prefer cookie method which is accepted answer. – Nurgiel Mar 30 '17 at 13:17
  • 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? – suchislife Jan 17 '18 at 19:56
21

$_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
  • 932
  • 5
  • 10
  • 7
    Why is this being voted up? harto's solution proves it untrue. – da5id Apr 16 '09 at 22:46
  • 1
    Yes agreed, but it doesn't answer the question and is in fact presenting misleading information. – da5id Apr 16 '09 at 23:28
  • 4
    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 Apr 17 '09 at 03:19
  • 1
    Cookies are no more secure, they're easily visible in most browsers. – Danny Tuppeny Mar 13 '12 at 12:43
  • 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. – Will Green Mar 15 '12 at 20:50
  • If you use a cookie to store session variable, you can have a big security issue in your code. If i change cookie data with your email? – elp May 13 '12 at 11:30
  • Which is only important if the value you are saving needs to be secure. – RationalRabbit Mar 07 '18 at 23:47
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'].'"';
Luis Melgratti
  • 11,881
  • 3
  • 30
  • 32
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>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
  • Not really answering the question – MaGnetas Dec 17 '13 at 20:08
  • 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. – user2954658 Dec 17 '13 at 22:07
  • 1
    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 = ''; 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. – MaGnetas Dec 18 '13 at 05:50
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

Community
  • 1
  • 1
Maffelu
  • 2,018
  • 4
  • 24
  • 35
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');
MSS
  • 3,520
  • 24
  • 29
1
<script type="text/javascript">
var foo="<?php echo $_SESSION['user_id']; ?>";
alert(foo);
</script>
Punam
  • 21
  • 1