Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reach php $_SESSION array in javascript?

Tags:

javascript

php

I am trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible??? I tried some ways but did not work like following:

var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);

and:

var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);

It is either show a text or never alert at all

like image 892
Basel Avatar asked Jun 24 '13 08:06

Basel


People also ask

Can JavaScript access PHP session variable?

Your answer Hello @kartik, You can't set a server session variable directly from JS. //preliminary code Session::put('roleID', $request->input('role') );

Can I get session value in JavaScript?

Session is a variable on the backend server side, while JS is a previous script. There is no ready-made method in JS to get the value of Session, and it needs to be obtained through the server language. For example, java can be used to get the value of Session and assign it to JS variable.

How can I access session variable in PHP?

To set session variables, you can use the global array variable called $_SESSION[]. The server can then access these global variables until it terminates the session. Now that you know what a session is in PHP and how to start one, it's time to look at an example and see how it works.

What is the purpose of PHP $_ session [] array?

We need a session array to retain the data in different pages. Session arrays are like session variables which maintain a unique link between user's web page and the server.


2 Answers

Just echo it:

var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);

You need tertiary operator, as false is echoed as empty string so it would lead to var session = ; which is a JS syntax error.

like image 103
Voitcus Avatar answered Oct 12 '22 01:10

Voitcus


If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,

<?php
session_start();
$_SESSION["x"]="y";
?>

<script>
 var session = eval('(<?php echo json_encode($_SESSION)?>)');
 console.log(session);

//you may access session variable "x" as follows
alert(session.x);
</script>

But note that, exporting all $_SESSION variable to client is not safe at all.

like image 26
Kemal Dağ Avatar answered Oct 12 '22 02:10

Kemal Dağ