Creating a PHP Session Using jQuery / JS

When loading the page, I want to check if the PHP session variable exists:

  • If so, the alert()contents
  • If it is not, create it and save the current time.

Here is my code:

$(document).ready(function(){

  <?php if(session_id() == '') { session_start(); } ?>

  if (!<?php echo isset($_SESSION['lbBegin'])?'true':'false'; ?>) {
    <?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

}); 

This code works in the sense that loading the first page does not create alert(), and the update shows the time, however each click of the update / link subsequently changes the time. I expected time to remain unchanged throughout the session.

What did I do wrong?

+4
source share
1 answer

You need to add session_start()at the very beginning and check if the session variable exists. Do this:

<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){

  if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
    // And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
    <?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

});
</script>

AJAX bit fix:

<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){

  if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
    // And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
    $.getScript("setTime.php");
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

});
</script>

Inside, setTime.phpadd the code:

<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
+1
source

Source: https://habr.com/ru/post/1624770/


All Articles