Lee
Lee

Reputation: 1495

Creating a PHP Session using jQuery / JS

On page load, I want to check if a PHP Session variable exists:

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 the first page load doesn't produce an alert() and a refresh shows the time, however every refresh / link click afterwards changes the time. I was expecting the time to stay the same during the entire session.

What have I done wrong?

Upvotes: 4

Views: 232

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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

<?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>

Correcting the AJAX Bit:

<?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 the setTime.php add the code:

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

Upvotes: 1

Related Questions