Saturday, February 6, 2016

Rename all Files in Folder According to Date in PHP


In any operating System like window, ios or Linux does not support same name files in the same directory so when you try to copy other files with same name it's overwrite or rename new file according to operating system functionality.
Now when you collect many pictures or documents in any specific folder for the long term then you may fetch this problem many times and for that you want to find some solution like separate each file name according to date modify or created. so it's easy to do this using PHP language.
In PHP for get all files in directory use `readdir()` function.get all files list in some specify directory as below.

if ($handle = opendir('.')) { //Here list directory and files of present folder
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          echo $entry; 
 }
    }
    closedir($handle);
}

Here below you can insert folder path in `opendir()`.for example if you want to get all list from 'News/Info/' directory than enter `opendir('News/Info/')`.Here below display list of all files.now you want date of file for that use `filemtime()` function as below.

if ($handle = opendir('.')) { //Here list directory and files of present folder
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          echo filemtime($entry); //Here if file in any folder than must put folder name like filemtime('News/Info/'.$entry) 
 }
    }
    closedir($handle);
}

Now you want to rename all listed file according to file time.Note that here below time display as timestamp so you must convert to date time.and for rename any file you must know file extension for that `pathinfo()` function use.so complete code for rename all files according to file date as below.

if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
         $filedate = date('d-M-Y H-i-s',filemtime($entry));
         $extension = pathinfo($entry, PATHINFO_EXTENSION);
  rename($entry,$filedate.'.'.$extension); //If here file is not in code directory than must enter folder name like rename('News/Info/'.$entry,'News/Info/'.$filedate.'.'.$extension); 
 }
    }
    closedir($handle);
}

Here from below date function you can convert file name like `06-Feb-2016 08-10-12` for using PHP date function you can change this format also.

No comments :

Post a Comment