April 16, 2012

How do create a global visit counter that echoes an image for every visit?

Question by Nathan Bankhead

Basically I want to create a global visit counter of a web page, then I want to display an image for every visit. So if 10 people have visited the page, 10 random images from the server will be echoed on that page. When the 11th visitor arrives on the page a new random image will be echoed and so on…

So I need help with two things really –

  1. I have a very basic visit counter but it only works in sessions, I need it to work globally?
  2. How do I echo images according to the number of visits?

Here is the basic code I have for a visit counter:

if(isset($_SESSION['views']))
   $_SESSION['views']=$_SESSION['views']+1;
else
   $_SESSION['views']=1

echo "Page views: ".$_SESSION['views'];

I am still a massive beginner at php and any help would be hugely appreciated 🙂

Thanks guys.

Answer by Starx

SESSIONS are NOT for global storage.

They are only alive till the website is open.

You should use database to store the global variable.


Now, coming to the image display part. You can name of images with number specific to no of visits.

For example:

4.jpg will be the Image that is when to the fourth guy

Next, you can use a simple snippet like this

$visitCounter = "?"; //Get the count using a logic
echo "<img src="$visitCounter.jpg" />"; //Use it to create a image path

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!