phpsessioncounterincrementdecrement

increment/decrement $_SESSION variable when button is click. Hint header()


I Initialized a $_SESSION variable = 1 and I want to increment/decrements its value when a link is click. And the links will reload the page then echo the value of the $_SESSION. I was given a hint redired using header() but I still can't figure it how.

<?php  
        if (isset($_SESSION['count'])) {
            $count = $_SESSION['count'];
        } else {
            $count = '';
        }
    ?>
    <a href="index.php?inc=TRUE">Increment</a>
    <a href="index.php?dec=TRUE">Decrement</a>
    <?php if (isset($_SESSION['count'])): ?>
        <?php echo $count ?>
    <?php endif ?>

Solution

  • <?php 
        session_start();
    
        if(!isset($_SESSION['count'])
            $_SESSION['count'] = 0;
    
        $counter = $_SESSION['count']; 
        $counter = (int)$counter;
    
        if (isset($_GET['inc'])==TRUE) { 
            $counter++;
            $_SESSION['count'] = $counter; 
            header("Location: index.php"); 
        }
    
        if (isset($_GET['dec'])==TRUE) { 
            $counter--;
            $_SESSION['count'] = $counter; 
            header("Location: index.php"); 
        }
    ?> 
    

    Also You may need to cast $counter to int..