Autoincrement numeric variable in PHP on Refresh

前端 未结 4 1601
一生所求
一生所求 2021-01-24 08:56

How do I use PHP to auto-increment a numeric variable on page refresh?

Foe example, for $i=10 there is an output of this:

Page has be

相关标签:
4条回答
  • 2021-01-24 09:14

    if it's for the same user session, use a session

    session_start();
    if (!isset($_SESSION['counter'])) $_SESSION['counter'] = 0;
    $_SESSION['counter']++;
    

    otherwise, if you want the same count for all users, use database

    0 讨论(0)
  • 2021-01-24 09:21

    You can easily do it with the help of cookies

    $cookieName = 'count';
    $count = isset($_COOKIE[$cookieName]) ? $_COOKIE[$cookieName] : '';

    $newCount = $count+1;
    setcookie($cookieName,$newCount);

    $count will return back the updated value

    0 讨论(0)
  • 2021-01-24 09:22

    You would need to store its state somewhere, perhaps in the $_SESSION.

    session_start();
    
    $i = isset($_SESSION['i']) ? $_SESSION['i'] : 0;
    
    echo ++$i;
    
    $_SESSION['i'] = $i;
    
    0 讨论(0)
  • 2021-01-24 09:30

    you need to store the counter somewhere like a file, database, cookie or session variable.

    <?php
        if (!isset($_COOKIE['visits']))
            $_COOKIE['visits'] = 0;
        $visits = $_COOKIE['visits'] + 1;
        setcookie('visits', $visits, time()+3600*24*365);
    ?>
    
    <?php
        if ($visits > 1) {
            echo("This is visit number $visits.");
        } else { // First visit
            echo('Welcome to my Website! Click here for a tour!');
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题