0

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?

RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
Xavier Xames
  • 27
  • 1
  • 7
  • How long after the first visit are you talking about? – RiggsFolly Oct 04 '21 at 14:46
  • Light reading [that may be useful to you](https://stackoverflow.com/questions/1516266/how-long-will-my-session-last) – RiggsFolly Oct 04 '21 at 14:52
  • @RiggsFolly let's say 24 hours. But is it possible to stick to session_start() without using cookie? – Xavier Xames Oct 04 '21 at 15:00
  • I coud steal a session of another user this way – Max Muster Oct 04 '21 at 19:35
  • Adding the session identifier to the URL query parameters opens you up to [session hijacking attacks](https://shiflett.org/articles/session-hijacking). This really is a big no-no. – vixducis Oct 04 '21 at 20:19
  • @Max Muster No it's not the session identifier in the URL parameter, it's just a string text that I will grab from the URL. Basically they come to the site from another source with that URL parameter. Now if people remove the URL parameter and visit this page again, I still want the value of the URL parameter saved in their session and pass it through AJAX post to another API. – Xavier Xames Oct 04 '21 at 20:54

1 Answers1

1

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']; }
Xavier Xames
  • 27
  • 1
  • 7