0

I am creating a PHP session using the following code:

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

How can I access the variable loggedin in Javascript? In other words, I want to check in Javascript if the variable 'loggedin' is set or not.

1
  • You could write $_SESSION['loggedin'] into a <script> block so that by the time it makes it to the client for JavaScript to evaluate, the variable will be written in... but if all you are trying to do is detect whether or not the user is logged in, why not have PHP output the page with some specific element or ID that you can detect via JavaScript easily? Commented Aug 10, 2011 at 19:03

2 Answers 2

5

The only way to do this is to write the value into a script block on the page as a JS variable, and reference it that way, or to make an AJAX request to a page that then returns the logged in status. There's no way for your client to directly access the session state in any server language.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't — at least not directly.

PHP runs on the server, but JavaScript runs in the browser.

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.