Is it possible to access session variables made in from JavaScript, and how can I replicate this PHP code in JavaScript?
if(empty($_SESSION['name'] {
echo 'foo';
}
Is it possible to access session variables made in from JavaScript, and how can I replicate this PHP code in JavaScript?
if(empty($_SESSION['name'] {
echo 'foo';
}
If you setup your javascript to be parsed by php, you can access session vars just like you can in php:
// Test.php
<?php session_start(); ?>
<?php $_SESSION['foo'] = 'bar' ?>
<script type="text/javascript">
alert('<?php echo $_SESSION['foo'] ?>');
</scrip>
<?php var_dump($_SESSION['foo']) ?>
Sorry but you can't :(
First a little Background:
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. From http://www.php.net/manual/en/intro.session.php
Basically Sessions involve storing data server side and storing an ID in a cookie client side. Meaning that JS could in theory access the cookie but then all you would have would be access to the PHPSESSID variable (the session id).
To achieve what you are trying to do, you can use ajax. (Contrary to the popular misconception) ajax requests still provide the server with all the information it needs to access cookies and sessions.
So simply make a server side script like getName.php which contains:
if(!empty($_SESSION['name'])) {
echo $_SESSION['name'];
}
And use ajax to get the response :)
well ... ajax is nice and everything, but if you really want, you can just print them as variables in your tag in the head and access them via js that way. I've never done that with session variables, but I print out values from php (mysql) in that manner all the time