Home > database >  Unable to Rename the latest file in a folder with PHP
Unable to Rename the latest file in a folder with PHP

Time:02-04

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

?>

CodePudding user response:

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.

  •  Tags:  
  • Related