0

I want to rename the latest added file from a folder, but somehow my code isn't working. Could please help!

For example, if the latest file is "file_0202.json" And I want to Change it to "file.json"

Here is my Code

<?php

$files = scandir('content/myfiles', SCANDIR_SORT_DESCENDING);
$selected_file = $files[0];

$new_filename = preg_replace('/_[^_.]*\./', '.', $selected_file);

if(rename($selected_file, $new_filename, ))
{
echo 'renamed';
}
else {
echo 'can not rename';
}

?>
Ranjit T
  • 53
  • 5
  • `SCANDIR_SORT_DESCENDING` is _alphabetical_ sorting, what does that have to do with "latest"? – CBroe Feb 03 '22 at 09:52
  • 1
    You are trying to rename the source file in the current script execution folder. But that is not where it is located, it is located in `content/myfiles`. You need to prepend the path to both the old and new file name. – CBroe Feb 03 '22 at 09:56
  • @CBroe oh yeah, you are right. is there a function to point the latest file ? – Ranjit T Feb 03 '22 at 10:01
  • No, the functions for reading from a directory don't generally provide that option, you'll have to sort them yourself, https://stackoverflow.com/questions/2667065/how-to-sort-files-by-date-in-php – CBroe Feb 03 '22 at 10:11
  • @CBroe Thanks a lot for the reference. So from there, if i happen to set the latest file name to "$selected_file", but still this won't work, yeah ? rename($selected_file, $new_filename). Its bugging me so much – Ranjit T Feb 03 '22 at 10:19
  • 1
    As I said, you need to prepend the proper path. – CBroe Feb 03 '22 at 10:21

1 Answers1

2

It's better if you use glob(). glob() returns the path and filename used.

Then you have to sort by the file that was last changed. You can use usort and filemtime for that.

$files = glob('content/myfiles/*.*');

usort($files,function($a,$b){return filemtime($b) <=> filemtime($a);});

$selected_file = $files[0];
$new_filename = preg_replace('/_[^_.]*\./', '.', $selected_file);
if(rename($selected_file, $new_filename))
{
  echo 'renamed';
}
else {
  echo 'can not rename';
}

Instead of *.* you can restrict the searched files if necessary. As an example *.json . Be careful with your regular expression so that it doesn't change a path.

jspit
  • 7,276
  • 1
  • 9
  • 17