1

I found many answers related to ASP.NET MVC as well as PHP-related one (e.g. How to access PHP session variables from jQuery function in a .js file? )

However I would like to understand if it's possible (via Chrome DevTools' console or in a .HTML page) to access a variables set in PHP by:

$_SESSION['varXY'] = 'abc';
2
  • You could make an AJAX request to a PHP file to get the session info. Commented Nov 20, 2015 at 18:06
  • You cannot directly expose the session. You can print the session info into global javascript variables(bad), you can convert your session variables to cookies (bad), you can use an AJAX request to hit the server and get the sessions back(this should do for you) Commented Nov 20, 2015 at 18:06

1 Answer 1

3

It is not possible to access PHP Session Variables in .html or .js files directly. However you can print/echo PHP variables in html.

If you want these variables as JS variables that can be done but it is not a good practise to do that.

Better way of accessing PHP variables in JS is via AJAX and PHP file. An example would be like below -

// sessionInfo.php
$sessions = array("var1" => $_SESSION['varXY'], "var2" => $_SESSION['abc']);
echo json_encode($sessions);

And in JS file -

$.ajax({url : sessionInfo.php, method: "get", dataType:"json" success: function(response){//Your session variable values here ...}});
Sign up to request clarification or add additional context in comments.

2 Comments

than you. however how would I do that if I can't access server to upload a php? (I actually can but I can't find where that session variable is actually defined)
$_SESSION are global environment variables. If you know the key of the session variable, you can access it from any of the php files. No need to include anything. If you don't know the session keys, then you can dump all the session variables and see like this - var_dump($_SESSION);

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.