在多个子文件夹中搜索最新图像,抓取它重命名并删除子文件夹和图像

I have the following script for a webcam that upload pics every minute that runs with cron job. It searches for images in a specific folder grabs and renames the latest, copy it to a new destination and delete the rest images.

Here is the script:

<?php
date_default_timezone_set("Europe/Athens");


//
//Watch Folder
$dir = "../upload";        
//File extention to watch
$pattern = '/^.(jpg)$/';
//Newest file check
$newstamp = 0;           
$newname = "";

if ($handle = opendir($dir)) {              
       while (false !== ($fname = readdir($handle)))  {           
         // Eliminate current directory, parent directory           
         if (preg_match(' /^\.{1,2}$/',$fname)) continue;           
         // Eliminate other pages not in pattern           
         if (! preg_match('/\.(jpg)$/',$fname)) continue;           
         // -------------

         // Collecting images
         $pinakas[] = $fname;
       }

       // Sort Images
       sort($pinakas);
       // Count
       $posot = count($pinakas);
       // Take the before last position 
       if ($posot>1) $newname = $pinakas[$posot-2];
       if ($posot==1) $newname = $pinakas[$posot-1];


}
closedir ($handle);

// $newname NEW IMAGE NAME
//COPY NEW IMAGE TO NEW PLACE

copy("../upload/$newname", "../camera1.jpg");



//DELETE IMAGES

$filesa = glob('../upload/*.jpg');

array_walk($filesa,'myunlink');

function myunlink($t)
{
    unlink($t);
}

?>

Now i have a new ip camera that upload a pic every minute but everytime in a different folder like this:

Time: 10:01 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/01/05[R][0@0][0].jpg
Time: 10:02 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/02/06[R][0@0][0].jpg
Time: 10:03 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/03/07[R][0@0][0].jpg

How do i now make the script to search all the subfolders of ..upload for latest jpg grab it, copy it to new place and delete all the subfolders and .jpg images of the ..upload folder?

Any help appreciated.

You can do this with recursive function:

function getJpgImages($dir, &$pinakas = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            if ( preg_match('/\.(jpg)$/',$path) )
                $pinakas[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $pinakas);
        }
    }
    return $pinakas;
}

and then remove your while loop and get images like this:

$pinakas = getJpgImages($dir);