Home > Enterprise >  Keep PHP session active after removing the URL parameter
Keep PHP session active after removing the URL parameter

Time:10-11

I'm trying to get the value of an URL parameter and save it to a JS variable using PHP session.

My URL: domain.com/?id=MYID

My PHP code:

session_start(); 
$_SESSION['id'] = $_GET['id']; 

And then I'm saving it in JS variable as:

<script type="text/javascript"> var id = '<?php echo $_SESSION['id']; ?>'; </script> 

My question is, is it possible to keep the value of $_SESSION['id'] even when I visit domain.com (without the id parameter on 2nd visit) with the same browser?

CodePudding user response:

I found the solution. I was defining the $_SESSION['id']Even when there is no URL parameter. So, when I visit the page without the URL parameter the $_SESSION['id']is still defining it's value with empty/nothing.

So to solve this, I added a isset condition to make sure it's only defining when the parameter is posted, otherwise keep the old one.

if(isset($_GET['id'])) { $_SESSION['id'] = $_GET['id']; }
  • Related