Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include image file with changing filename

Tags:

php

I am completely new to PHP so forgive me if this question seems very rudimentry. And thank you in advance.

I need to include a jpg that is generated from a webcam on another page. However I need to include only the latest jpg file. Unfortunately the webcam creates a unique filename for each jpg. How can I use include or another function to only include the latest image file? (Typically the filename is something like this 2011011011231101.jpg where it stands for year_month_date_timestamp).

like image 628
gijigogo Avatar asked Jul 12 '26 21:07

gijigogo


2 Answers

Easy way is to get the latest image with the help of the below code

$path = "/path/to/my/dir"; 

$latest_ctime = 0;
$latest_filename = '';    

$d = dir($path);
while (false !== ($entry = $d->read())) {
  $filepath = "{$path}/{$entry}";
  // could do also other checks than just checking whether the entry is a file
  if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
      $latest_ctime = filectime($filepath);
      $latest_filename = $entry;
    }
  }
}

// now $latest_filename contains the filename of the newest file

give the source of latest image to <img> tag

like image 76
Wazy Avatar answered Jul 14 '26 12:07

Wazy


Since the images are named via pattern which relates to the date, you should be able to just use:

$imgs = glob('C:\images\*.jpg');
rsort($imgs);
$newestImage = $imgs[0];
like image 37
ken Avatar answered Jul 14 '26 12:07

ken