Rotating background image (or other PHP function) in CubeCart templates

I have a site where the main site picks an image from a particular folder for the background every time you hit a page, rotating through the available images in a loop. We also have a CubeCart store, which has had the template skinned to fit the main site, so obviously enough, I wanted to have the same background image feature for the shop.

The thing with CubeCart templates is that you can’t just add php to the .tpl files – you have to do all your PHP jiggery pokery in include files, and assign values to object properties, and include a placeholder in the tpl.

There are two key CubeCart files to make this change over the whole shop:


First off you want to get your functions together from the main site. Mine all live in a lib.php file, but as I don’t need to load all of them into CubeCart, I pulled the relevant ones into a new file, /lib/php/rotatebg_lib.php. Now I can include this file in my original lib.php as well as in CubeCart, and reduce unnecessary memory overheads.

The system relies on three functions:

files_in_dir($start_dir) creates an array of the files in a directory. This is one of my standard ‘off the shelf’ functions

index_background_images() checks for files with a .jpg extentsion, creates an array of them and stores it in a $_SESSION variable, called only when a session is started. There are other ways of checking for file types – the most reliable is to mime_content_type() function, but if you trust the files on your server, my method is fine. If you are dealing with user uploaded files, remember you should NEVER trust the file to be what it says it is!

rotate_background() checks for a session, calls the indexing function if necessary and otherwise increments the index counter.


Now we need to include and run these functions in the CubeCart global index include.Line numbers may vary dependant on your template, but essentially you want to add this just after the $body template has been defined




And finally, insert VAL_CUSTOM_BACKGROUND into the index.tpl file. This needs to be added in the head section, I prefer the end of the head section as CSS latency will ensure that the rule is obeyed. Again, line numbers may vary.




Shazzamwhazzam. We are done.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *