PHP Image Switcher

in

Brief Overview

The PHP image switcher code I wrote is to switch images on a page refresh and specific screen size. This allows default header images for a page to be randomized until one is set in a CMS.

Design and Usage

The design is simple. Set an image directory, put all your specific sized images in it. Add a prefix to each image file name according to the size. Examples: 600_, 800_, 1400_, or 2000_. Start the web page on the index.php.

Hands On

Code

// File: index.php
<!doctype html>
<html lang="en">

<head>
    <title>Image Switcher</title>
    <meta name="Description" content="Switches images on screen responsiveness and display all at the same time." />
</head>

<body>
    <?php require 'img-switcher.php'; ?>
    <h1>Screen Responsiveness</h1>
    <picture>
        <source srcset="<?php echo $_SESSION['stdImg2000'] ?>" alt="responsive image" media="(min-width: 1400px)" />
        <source srcset="<?php echo $_SESSION['stdImg1400'] ?>" alt="responsive image" media="(min-width: 769px)" />
        <source srcset="<?php echo $_SESSION['stdImg800'] ?>" alt="responsive image" media="(min-width: 577px)" />
        <img srcset="<?php echo $_SESSION['stdImg600'] ?>" alt="responsive image" style="width: 100%; height: auto;" />
    </picture>

    <br /><br /><br /><br /><br />

    <h1>All at once</h1>
    <img src="<?php echo $_SESSION['stdImg2000'] ?>" alt="responsive image" />
    <img src="<?php echo $_SESSION['stdImg1400'] ?>" alt="responsive image" />
    <img src="<?php echo $_SESSION['stdImg800'] ?>" alt="responsive image" />
    <img src="<?php echo $_SESSION['stdImg600'] ?>" alt="responsive image" />
</body>

</html>
// File: img-switcher.php
<?php
session_start();
$imgpath = $_SERVER['DOCUMENT_ROOT'].'/phpimagesearch/images/new-images/';
$imgarrays = array("2000" => glob($imgpath."2000_*.jpg"),
			  "1400" => glob($imgpath."1400_*.jpg"),
			  "800" => glob($imgpath."800_*.jpg"),
              "600" => glob($imgpath."600_*.jpg"));
              
foreach($imgarrays as $imgSize => $imgArr){
    shuffle($imgArr);
    $_SESSION['stdImg' . $imgSize] = explode("C:/xampp/htdocs", $imgArr[0])[1];
}
?>

Running the Code

I used Xampp to allow me to install PHP and run the script. You can get my code from Github to use. After installing Xampp you can clone the code into the htdocs directory and start up the services. After the services are started, you can open a browser and go to http://localhost/PHP-Image-Switcher to see it working.

Demo

Unfamilar Terms

  • CMS
    • Is an acronym that stands for Content Management System.

Resources

About the author

For the last five years, Jacob Ashcraft has worked towards a Bachelors in Software Engineering at Snow College while raising a family. He currently is a husband, and a father of two children. He focuses on front-end development and enjoys C# and the Javascript languages. He enjoys reading fantasy novels, anything techy, and spending time with family.

Read next: