Picture of the Day in PHP
Posted in Site Updates, Tutorials April 6th, 2020 by dotcomboom
pog

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.

    <?php
        $today = (int)date('Yz');
        srand($today);
    
        $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.

<?php
    $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.


« « « Leave a comment » » »



RSS feed for these comments. | TrackBack URI