Image rotator with php and javascript

may 12, 2022

This is a demo for a discussion at Image slider/rotator php code help.

Following banner changes its image for every 30 seconds.

PHP (this page)

<?php
session_start();

/*save file index to session: make sure index file for first shown image (banner-2.jpg) is 0.
if you want to use other image, find its index by trial and error.*/
$_SESSION['iFile'] = 0;
?>

<img id="banner" src="banners/banner-2.jpg" alt="">
<script src="banner.js"></script>

javascript (banner.js)

'use strict';
{
	const tReqNxtBanner = 30 * 1000,//timeout to next banner request
		urlNxtBanner = 'banner.php',
		xhr = new XMLHttpRequest();//ajax
	
	function reqNxtBanner(){
		xhr.open('GET', urlNxtBanner);
		xhr.send();
	};
	
	//ajax response handler
	xhr.onreadystatechange = function(){
		try{
			if (this.readyState === XMLHttpRequest.DONE){
				if (this.status !== 200)
					alert('banner error: there was a problem with the request.');
				else{
					const json = JSON.parse(this.responseText);
					if(json.code < 1)
						alert('banner error: ' + json.msg);
					else{
						//update banner image
						document.getElementById('banner').src = json.msg;
						
						//delay to next banner request
						setTimeout(reqNxtBanner, tReqNxtBanner);
					}
				}
			}
		}
		catch(err){
			alert('banner error: ' + err.description);
		}
	};
	
	//1st request
	setTimeout(reqNxtBanner, tReqNxtBanner);
}

PHP (banner.php)

<?php
	define('DIR_BANNERS', 'banners/');

	session_start();
	
	//assume error unknown
	$response['code'] = 0;
	$response['msg'] = 'unknown error.';
	
	//error if file index isn't set by index.php
	if(!isset($_SESSION['iFile'])){
		$response['code'] = -1;
		$response['msg'] = 'session is not properly started.';
	}
	else{
		//read all files inside DIR_BANNERS subdir
		$entries = array();
		if($handle = opendir(DIR_BANNERS)){
			while(false !== ($entry = readdir($handle))){
				if($entry != '.' && $entry != '..'){
					$entries[] = DIR_BANNERS . $entry;
				}
			}
			closedir($handle);
		}
		
		//pick an image
		$entriesLen = count($entries);
		if($entriesLen == 0){
			$response['code'] = -2;
			$response['msg'] = 'no files found.';
		}
		else{
			$iFile = $_SESSION['iFile'];
			if($iFile < $entriesLen - 1){
				$iFile++;
				$response['code'] = 1;
			}
			else{
				$iFile = 0;
				$response['code'] = 2;
			}
			$response['msg'] = $entries[$iFile];
			$_SESSION['iFile'] = $iFile;//save to session for next use
		}
	}
	
	//always return json
	header('Content-type: application/json; charset=utf-8;');
	echo json_encode($response);
	exit;
?>

Comments