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

Antonella's avatar

PHP session : do not increment the session every time I refresh the page

I created this code that increments the session variable every time I click on the button. I just don't want it to increment every time I refresh the page:

	<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['add'])) {
       $_SESSION['attnum'] = 0; // Reset counter
   }
?>

<form method='post'>
<input name='add' type="submit" value='+'>
<h3><em>att<?php echo $_SESSION['attnum']++ ?>: </em></h3>
</form>

how can i set the session to increment only when i click on the button and not to increment when i refresh?

0 likes
8 replies
Tray2's avatar

Then remove the ++ from this line.

<h3><em>att<?php echo $_SESSION['attnum']++ ?>: </em></h3>
Tray2's avatar

That is because you need to hit an endpoint on the server to do it. What you did before when you hit the button was a page refresh.

You need to connect your button to an ajax request and when it hits the server you increment the session value.

Antonella's avatar

could you help me in this operation? if an example were possible? many thanks @tray2

Tray2's avatar

What is it that you are trying to achieve?

In what context are you going to use it?

Antonella's avatar

I'm trying to get a variable increment if and only if I press the button. I'll need that variable to iterate through an array @tray2

Tray2's avatar

You know that you can use foreach to do that or even a for loop since you can get the number of items in the array by using count.

foreach($yourArray as $value) {
     // use the $value for something	
}
for( $i = 0; $i < count($yourArray); $i++) {
	use $youraArray[$i] for something.
}

So there isn't any need to store a number for that.

newbie360's avatar

only modify $_SESSION['attnum'] when you click on submit button, so

<h3><em>att<?php echo $_SESSION['attnum'] ?>: </em></h3>

Please or to participate in this conversation.