This kinda long explanation so please bare with me.
Goal:
I have a list of directories within directories that have multiple files. Within this massive amount of directories are two files: users and config. In those files are strings that contain the string "mail3"(without quotes). I need to open all these directories, search for those two files, open them and replace the string with "mail"(without quotes) and then close the file.
Overview of script:
Basically what is going is im checking to see if the file is a directory, if true then open it, read the files...if the file matches one of two of my conditions, open the file check to see what lines match, replace the string, write the file and then close it.
Problems:
The problem is once the script is run my confirmation alert "Everything is ok" is sent to STDOUT, but when i open the files the "mail3" string still exists. I know that the file is being opened and the lines read because i changed the script to just output the lines of all the files and it did, but it is just not making the changes.
ANY help would be greatly appreciated. I found a way to do it in perl and shell scripting, but I am trying to get it to work in PHP because that is why i originally started with and couldn't get it to work....it is a matter or pride. I can't let this be something that i couldn't do.
//begin code
#!/usr/local/bin/php
<?
$dir = ".";
$dirHandle = opendir($dir) or die("Couldn't open $dir");
if (is_dir($dir)) {
while (FALSE !== ($dirFile = readdir($dirHandle))) {
if ($dirFile !=='.' && $dirFile !== '..') {
if (is_dir($dirFile)) {
$newDirHandle = opendir($dirFile) or die("Couldn't open sub-dir $dirFile");
while (FALSE !== ($newDirFile = readdir($newDirHandle))) {
if ($newDirFile !== '.' && $newDirFile !=='..' && $newDirFile ==='users' || $newDirFile ==='config') {
if (!copy($dirFile."/".$newDirFile, $dirFile."/".$newDirFile."orig")) {
print "Copied Failed for $newDirFile";
} elseif (!is_writable($dirFile."/".$newDirFile)) {
echo "The File isn't Writable so why continue\n";
exit;
}
$fh = fopen($dirFile."/".$newDirFile, 'r+') or die();
while (!feof($fh)) {
$lines = fgets($fh, 1024);
if (preg_match('/mail3/', $lines)) {
$lines = preg_replace('/mail3/','mail', $lines);
if (!fwrite($fh, $lines)) {
print "write failed";
exit;
} else {
print "Everything is ok\n";
}
}
}
}
}
}
}
}
}
?>
//end code
NOTE: i am running this from the command line and it is on Linux