简体   繁体   中英

How do I move a specified number of files automatically from one folder to another using PHP? (for use in WordPress plugin)

Using a WordPress plugin, I have an image carousel that displays all files within a specified folder.

I only want to display the last 24 images from that folder. One way I thought I could do this without editing the original plugin is have all files from the previous day move to a new folder when the first photo from the next day arrives. The file names contain a time stamp, because of this, I can't specify actual file names, just the type of file.

Unfortunately, I am completely new to PHP and Server Side Scripting and would appreciate any advice on how to solve this issue.

I believe you don't have to move the files, just read them and sort by date.

here's a conceptual how to, untested.


$files =[];
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort in reverse order
    krsort($files);

    for($i =0; $i < 24; $i++) {
      $file = $files[$i]
      echo "<img src='".$file."' />";
    }
}

good luck

Ok, You want to display only last 24 images from that folder.

You can get name of last 24 images by their modification time.

    $filelist = glob("/path/to/your_dir/*.{jpg,JPG,PNG,png,jpeg,JPEG}", GLOB_BRACE);

In php run a foreach loop for all the files in that directory, ,

    $i = 0;
    foreach($filelist as $key => $file){ 
       $temp_arr[$i]['mtime'] = filemtime($file); 
       $temp[$i]['filename'] = $file;
       $i++; 
    }

Then you can sort $temp_arr to retrive 24 latest images based on mtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM