1

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 been viewed <?php $i = 10; echo $i;?> times.

Now I want to increment $i when page refreshes so if user loads page 5 times, the number will increase by 5

4 Answers 4

8

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;
Sign up to request clarification or add additional context in comments.

8 Comments

this is my code, but it doesn't work.<h4>views<?php session_start(); $_SESSION['i']=100; $i = isset($_SESSION['i']) ? $_SESSION['i'] : 0; echo ++$i; $_SESSION['i'] = $i; ?></h4>
@enjoylie: You must call session_start() before any response body.
when i refresh the page, the unmber can't auo-increment one?
now, i put the <?php session_start();> code in my head.php before <!DOCTYPE html PUBLIC "-......and put the rest code in my main.php. but it still doesn't work. how to correct it. thank you
@enjoylife Change the 0 in my example to 100.
|
3

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

2 Comments

if i want to store the counter in cookie or session variable. how should i do? is there a tutorial about this thank you.
Cliff,when i refresh the page, why the number can't auo-increment one?thank you
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.