Sunday, May 13, 2018

file traverse and restore backup file in php

<?php
ini_set('max_execution_time', 300);
function DirLineCounter( $dir , $result = array('lines_html' => false), $complete_table = true )
  {

      $file_read = array('php','ctp');
      $dir_ignore = array();     
      $scan_result = scandir( $dir );     
      foreach ( $scan_result as $key => $value ) {       
          if ( !in_array( $value, array( '.', '..' ) ) ) {           
              if ( is_dir( $dir . DIRECTORY_SEPARATOR . $value ) ) {               
                  if ( in_array( $value, $dir_ignore ) ) {
                    continue;
                  }               
                  $result = DirLineCounter( $dir . DIRECTORY_SEPARATOR . $value, $result, false );                 
              }
              else {               
              $type = explode( '.', $value );
              $type = array_reverse( $type );
              $ext=$type[0];
              if( !in_array($ext , $file_read ) ) {
                continue;
              }
              $file=str_replace('.'.$ext, '', $value);
              $nameArr=explode('_', $file);
              if(in_array('12-05-2018', $nameArr)){
              $newFile=str_replace('_bck_12-05-2018', '', $value);
              //unlink($dir . DIRECTORY_SEPARATOR . $newFile); // for delete new file
              if(file_exists($dir . DIRECTORY_SEPARATOR . $newFile)){
                rename($dir . DIRECTORY_SEPARATOR . $newFile,$dir . DIRECTORY_SEPARATOR . $newFile.'_restore');               
              }
              rename($dir . DIRECTORY_SEPARATOR . $value,$dir . DIRECTORY_SEPARATOR . $newFile);
              $result['lines_html'][] = '<tr><td>' . $dir . '</td><td>' . $value.'-->'.$newFile. '</td></tr>';
              }
             
              }
          }
      }     
      if ( $complete_table ) {   
        if(!empty($result['lines_html'])){
          $lines_html = implode('', $result['lines_html']);
        } else {
          $lines_html='';
        }
        return '<table><tr><td style="width: 60%; background-color:#ddd;">Dir</td><td style="width: 30%; background-color:#ddd;">File</td></tr>' . $lines_html . '</table>';       
      }
      else {
        return $result;
      }     
  }
  echo DirLineCounter( '../' );

2 comments: