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.

 http://septiadi.com/2011/06/22/php-auto-replace-multiple-files-content/
Advertisements

One response to “PHP Auto Replace Multiple Files Content

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: