Skip to content
Advertisement

Unable to Rename the latest file in a folder with PHP

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';
}

?>

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement