Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TwinsD's avatar

Sessions help

I'm having a hard time trying to work with sessions. Why are my sessions being reset here?

I want to be able to change the session variables between pages and for them to stay constant but they reset every time i click the link. I have two pages, session1.php and session2.php.

Once the session is created, my IF session_status should prevent the reassignment of the randomNumber, or am I wrong?

My code:

	<?php
if (session_status() === PHP_SESSION_NONE) {
  session_start();
  $_SESSION["randomNumber"] = random_int(1, 100);
  session_write_close();
}
 
echo "<a href='session2.php'>Link to Session2</a><br>";
echo "this is session1.php";
echo '<br>';
echo $_SESSION["randomNumber"];
 
 
-----------------------------------------------
 
<?php
if (session_status() === PHP_SESSION_NONE) {
  session_start();
  $_SESSION["randomNumber"] = random_int(1, 100);
  session_write_close();
}
 
echo "<a href='session1.php'>Link to Session1</a><br>";
echo "this is session2.php";
echo '<br>';
echo $_SESSION["randomNumber"];

0 likes
5 replies
Snapey's avatar

why use php session with Laravel helpers? your code makes no sense?

TwinsD's avatar

@Snapey I don’t know what a laravel helper is. I’m just learning php.

My expectation is that the random number won’t be reset each time I change pages because the session is active. Is this not the case?

gych's avatar
gych
Best Answer
Level 29

Use isset to check if $_SESSION['randomNumber'] exists

if (!isset($_SESSION["randomNumber"])) {
    $_SESSION["randomNumber"] = random_int(1, 100);
}

Once you start using the Laravel framework you can use the Laravel session helper https://laravel.com/docs/11.x/session

TwinsD's avatar

@gych thank you, I guess it’s wrong to assume that checking the status is enough to only load it once?

gych's avatar

@TwinsD

Checking the session status is good but you then also have to check if the session already contains the randomNumber otherwise it will get changed

if (session_status() === PHP_SESSION_NONE) {
    session_start();

    if (!isset($_SESSION["randomNumber"])) {
  		$_SESSION["randomNumber"] = random_int(1, 100);
	}

    session_write_close();
}
1 like

Please or to participate in this conversation.