06 Apr 2020 @ 9:44 PM 

I’ve been working on a revamp of my site! In doing so I’ve been practicing some PHP; one thing I wanted to do was have a randomized image on the homepage that would change every day. Looking around online I didn’t find many drop-in solutions I could just stick on the page, so I pieced together my own; and PHP actually makes it rather simple.

        $today = (int)date('Yz');
        $files = glob('photography/*.jpg');
        $file = array_rand($files);
        echo '<a href="[#root#]photography/"><img src="' . $files[$file] . '" alt="Picture of the day" style="border: 3px solid #444"></a>';

To explain, $today is set to the current date in the Yz format which is in the form of year and day in the year; for example, if today is 4/6/2020, it would come out to 202097. Tomorrow, it’d be 202098. That is converted from a string into an integer with (int), as it is going to seed PHP’s random number generator with srand(). Otherwise, the output would be random on every refresh.

glob() is then used to get all the jpg files in the photography directory and store that as $files. array_rand() is used to select one item’s index value at random from that array. The filename as $files[$file] is then concatenated and printed into the HTML with echo.

Date Taken/Exif Information

If desired, you can display other information about the image as well later down the page. I’ve done this to show the date the image was taken. This too is fairly simple when you get down to it, provided that your image does have this in its Exif metadata.

    $exif = exif_read_data($files[$file], 'IFD0');
    $takenDate = strtotime($exif['DateTime']);
    echo date('F j, Y', $takenDate);

exif_read_data() is used to read this information. The DateTime IDF0 attribute is fed into strtotime() so it’s understandable by PHP and then echoed out as a new human-readable format with date(). And that’s about it!

Here’s a place with some more Exif information in case you’re into experimenting. Also check out the PHP documentation.

Posted By: dotcomboom
Last Edit: 27 May 2020 @ 01:04 PM
Categories: Site Updates, Tutorials


Responses to this post » (None)

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

 Last 50 Posts
Change Theme...
  • Users » 1
  • Posts/Pages » 77
  • Comments » 8
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight