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';
Community
  • 1
  • 1
dragonmnl
  • 14,578
  • 33
  • 84
  • 129
  • You could make an AJAX request to a PHP file to get the session info. – Jay Blanchard Nov 20 '15 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) – Ohgodwhy Nov 20 '15 at 18:06

1 Answers1

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 ...}});
Chandan
  • 1,128
  • 9
  • 11
  • 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) – dragonmnl Nov 20 '15 at 19:11
  • $_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); – Chandan Nov 21 '15 at 06:31