file_put_contents and file_get_contents replacement code

<?php

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function get_file_contents($filename)

      /* Returns the contents of file name passed

      */
      {
      if (!function_exists('file_get_contents'))
      {
      $fhandle = fopen($filename, "r");
      $fcontents = fread($fhandle, filesize($filename));
      fclose($fhandle);
      }
      else
      {
      $fcontents = file_get_contents($filename);
      }
      return $fcontents;
      }
?><?php

function openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith)
{
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";

if ($handle = opendir("$parentDirectory")) {
    while (false !== ($file = readdir($handle))) {
        if (($file != "." && $file != "..") && !is_dir($file)) {
          chdir("$parentDirectory"); //to make sure you are always in right directory
         // echo "$file\n";
         $holdcontents = file_get_contents($file);
         $holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);
         file_put_contents($file, $holdcontents2);
         // echo "debug here- line 1\n";
         // echo "$file\n";

        }
        if(is_dir($file) && ($file != "." && $file != ".."))
        {
        $holdpwd = getcwd();
        //echo "holdpwd = $holdpwd \n";
        $newdir = "$holdpwd"."/$file";
        //echo "newdir = $newdir \n";  //for recursive call
        openFileSearchAndReplace($newdir, $searchFor, $replaceWith);
        //echo "debug here- line 2\n";
        //echo "$file\n";
        }
    }
    closedir($handle);
 }
}

$parentDirectory2 = $argv[1];
$searchFor2 = $argv[2];
$replaceWith2 = $argv[3];

//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n'$searchFor2' with '$replaceWith2' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: '$parentDirectory2'\n";
echo "command written by Kolapo Akande :) all rights reserved :)\n";

 $holdpwd = getcwd();
 //echo "$holdpwd\n";
chdir($parentDirectory2);
openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);
exit;
?>
This entry was posted in php. Bookmark the permalink.

Leave a Reply