Welcome to SO! As some of the other answers have already stated, Browser sessionStorage
that is accessible via JavaScript
and other client scripting languages, is not the same as PHP
$_SESSION
storage accessible on the server side. When should I use PHP Session vs Browser Local Storage vs JavaScript Object Parameters?
However, here is an example that would take the PHP
session variable value of $_SESSION['numOfPlayers'];
and set that as a JavaScript
variable numOfPlayersPHPSession
, that in turn could be set into client session storage (this won't work on SO or most online tools as session/local storage is typically locked down, but you should be able to test locally assuming proper permissions/config).
Also, this is a loose example, so you would still need to make sure and follow best security practices when rendering PHP
values into JS
variables to be used in client side scripting, etc.
<?php
session_start();
?>
<!DOCTYPE html>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Use null coalesce to make sure we set a value / 0 if no players
$numOfPlayers = $_POST['numOfPlayers'] ?? 0;
$_SESSION['numOfPlayers'] = $numOfPlayers; //It works until here
}
?>
<html>
<body>
<!--Code-->
<!--<script src="Script.js"></script>-->
<script type="text/javascript">
// In place of calling Script.js, embedding code here for example
let numOfPlayersPHPSession = <?php echo $_SESSION['numOfPlayers']; ?>;
sessionStorage.setItem('numOfPlayers', numOfPlayersPHPSession);
let numOfPlayers = Number(sessionStorage.getItem('numOfPlayers'));
// alert(numOfPlayers); or console.log(numOfPlayers);
</script>
</body>
</html>
If you go to the example at the below link and click "Execute code" (which has some of the $_SESSION
/ $_POST
logic commented out due to sandbox limitations), you will see that the value of 5
is set on a JS
variable coming from the PHP session value, and then that could be set into sessionStorage
. http://sandbox.onlinephpfunctions.com/code/285dbdec5446316c712dd49f895039eec8c4c915

Another item of note, if using client sessionStorage
, you may want to add additional checks to your JS
logic to ensure the browser window / application supports I/O with local/session storage, as outlined here: Most elegant way to check sessionStorage support?