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
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
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
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;
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!');
}
?>