SuperGeekery: A blog probably of interest only to nerds by John F Morton.

A blog prob­a­bly of inter­est only to nerds by John F Mor­ton.

Use a cookie to iterate between visits with PHP.

Here’s a small code snip­pet that I use to incre­ment a val­ue between vis­its using a PHP cook­ie.

I use it, for exam­ple, when I have 3 dif­fer­ent images that could go on a page, and I want to serve up the next one in the sequence on sub­se­quent vis­its to the page. I just use the “$num” where appro­pri­ate.

You can edit the 2’ in line 14 to change the wrap around val­ue to suit your needs. Hap­py PHPing.

<?php
	///////////////////////////////////////////////////////////
	//- Purpose: increment from 0 - 2, then loop back around //
	///////////////////////////////////////////////////////////

	// Is a cookie set already?
	if ($_COOKIE['numcycle']!='') {
		// If cookie was corrupted, it will return 0
		// when evaluated as in int.
		$num = (int)$_COOKIE['numcycle'];
		$num++;
		// if the newly iterated $num is over our limit,
		// in this case 2, then reset it to 0
		$num = $num <= 2 ? $num : 0;
		// now reset the cookie with the new number
		setcookie('numcycle',$num,time() + (86400 * 30)); // 86400 = 1 day
	} else {
		// Cookie wasn't set, so let's set one.
		setcookie('numcycle','0',time() + (86400 * 30)); // 86400 = 1 day
		$num = 0;
	}

	echo $num;
?>
QR code for the Use a cookie to iterate between visits with PHP.

Link to this page