Blog > detail

Just my tiny mind

PHP Auto Replace Multiple Files Content

26-2-2012 Admin General 2 Comments

PHP Auto Replace Multiple Files Content

Previously my best friend told me about his problems in php. He has a bunch of PHP file that already outdated.These files use PHP 4 format. He requested me if there is a way to change the format <? used in those files into <?php that used in current PHP format. Therefore, I made a PHP script to do such thing.


This script has feature:

  • List all files in current folder except the script it self
  • Read each file one by one
  • Replace requested string
  • Save it

This is the script:

<?php

//if file is too many, there is a possibility that the script exceed the max exection time

$this_file = 'index.php';//this is the script file for exception

if ($handle = opendir('.')) {

while (false !== ($file = readdir($handle))) {

if ($file != "." && $file != "..") {

echo "$file\n";


if($file != $this_file){


$handle2 = fopen("$file", "rb");

$contents = '';

while (!feof($handle2)) {

$contents .= fread($handle2, 8192);

}

$contents = str_replace("<?", "<?php", $contents);// for replacing <? into <?php

//for replacing deprecated function, you need regex

echo htmlspecialchars($contents).'<hr><br>';

fclose($handle2);


$fp = fopen("$file", 'w');

fwrite($fp, $contents);

fclose($fp);

}

}

}

closedir($handle);

}

?>


Just copy the script into a folder where resides the files that you want to replace the content.

PHP Auto Replace Multiple Files Content PHP Auto Replace Multiple Files Content PHP Auto Replace Multiple Files Content

PHP Auto Replace Multiple Files Content PHP Auto Replace Multiple Files Content PHP Auto Replace Multiple Files Content

PHP Auto Replace Multiple Files Content

word word

PHP Auto Replace Multiple Files Content

PHP Auto Replace Multiple Files Content

PHP Auto Replace Multiple Files Content