Press "Enter" to skip to content

Create an efficient Banner Rotator in Json and PHP

Over the years, every Developer has sooner or later faced this “dilemma”.
Insert a Banner, Text or Link in a predefined position, randomly; the purpose is to show a different Image or Link each time a page loads. A common called “Banner Rotator” to be precise.

Technically, there are many ways to create this system.
Today, we want to share a Simple and Effective system, to create this system, using 1 file in JSON, and few lines of PHP.

The structure is very simple and accessible to everyone:

The JSON file will contain the Data you want to show (images, texts and links)
The PHP code will import the data on your page
The DIV code will show the data on your page

This system is solid, non-invasive, simple to compile and can be implemented on any PHP page in a few minutes.
JSON is capable of containing even discrete quantities of data without any particular problems, so you can add new fields and expand the list of data to be displayed.
Let’s start with the structure of the .json file which we will call “data.json”, but you can renamed as your needs.

{
“banners”: [
{
“text”: “Your Text 1”,
“image”: “image1.jpg”,
“link”: “https://website1.com”
},
{
“text”: “Your Text 3”,
“image”: “image2.jpg”,
“link”: “https://website2.com”
},
{
“text”: “Your Text 3”,
“image”: “image3.jpg”,
“link”: “https://website3.com”
}
]
}

Once you have compiled this file with your data with your favorite text editor, save and upload it to your web space in the position most suited to the project. Afterwards, we just need to insert a small PHP Code, which reads the data present in the Json file we just created. You can insert this code on the page where you want to display the banners, at the beginning of the code or the tag.

<?php
// Read the contents of the JSON file
$jsonData = file_get_contents(‘data.json’);
$data = json_decode($jsonData, true);

// Get a random banner
$banners = $data[‘banners’];
$randomBanner = $banners[array_rand($banners)];
?>

Now, let’s create a div, which you can insert into the page, in the position you want; remember that if you use images of a certain weight and size you may need to add CSS to make the images compatible with mobile devices.

<a href=”<?php echo $randomBanner[‘link’]; ?>” rel=”noopener” target=”_blank” title=””>
<p><?php echo $randomBanner[‘text’]; ?></p><br>
<img src=”<?php echo $randomBanner[‘image’]; ?>” alt=””>
</a>

In the code, the div indicates the position; the php code displays the data of the fields present in the .json file.
Easy and Fast.

Life as a Developer can sometimes be simpler!

ScriptNet Solutions Blog

Read More