我正在研究一个脚本,它用一个字符串替换目录和子目录中的所有文件,以摆脱我们的软件显示的通用错误消息。在PHP中循环浏览目录?
我使用单个目录中的所有文件很容易地工作,但后来我们在一个包含子目录的文件夹中运行它,正如您可能猜到的那样,它会抛出很多错误。我完全忘记了子目录。
所以,现在我正在制作一个可以与子目录一起工作的脚本,但我很难过。
这里是我的代码:
<?php
$files = explode("\n", shell_exec('ls'));
$count = 0;
foreach ($files as $file)
{
if (empty($file) || $file == $_SERVER['SCRIPT_NAME'])
{
continue;
}
if (is_dir($file))
{
echo "Copying to {$file}/{$_SERVER['SCRIPT_NAME']}\n";
copy($_SERVER['SCRIPT_NAME'], $file . "/" . $_SERVER['SCRIPT_NAME']);
exec("php {$file}/{$_SERVER['SCRIPT_NAME']}");
unlink($file . "/" . $_SERVER['SCRIPT_NAME']);
continue;
}
$fh = fopen($file, 'w');
fwrite($fh, '<!-- Generated %T by %h (%s) -->');
fclose($fh);
echo "Rewrote {$file}\n";
$count++;
}
echo "Finished. Rewrote {$count} files. Don't forget to delete {$_SERVER['SCRIPT_NAME']}.\n";
?>
它结束了这个输出:
[[email protected] orgytest]# php p.php
Rewrote blah
Rewrote dfas
Rewrote dfasfsdjkfjsa
Rewrote dfdsafdsaf
Rewrote dfsaf
Rewrote orgy
Rewrote query
Rewrote scsew
Copying to test/p.php
Rewrote blah
Rewrote dfas
Rewrote dfasfsdjkfjsa
Rewrote dfdsafdsaf
Rewrote dfsaf
Rewrote orgy
Rewrote p.php
Rewrote query
Rewrote scsew
Copying to test/test/p.php
PHP Warning: copy(test/test/p.php): failed to open stream: No such file or directory in /root/orgytest/test/p.php on line 15
Could not open input file: test/test/p.php
PHP Warning: unlink(test/test/p.php): No such file or directory in /root/orgytest/test/p.php on line 17
Copying to test2/test/p.php
PHP Warning: copy(test2/test/p.php): failed to open stream: No such file or directory in /root/orgytest/test/p.php on line 15
Could not open input file: test2/test/p.php
PHP Warning: unlink(test2/test/p.php): No such file or directory in /root/orgytest/test/p.php on line 17
Finished. Rewrote 9 files. Don't forget to delete test/p.php.
Copying to test2/p.php
<!-- Generated %T by %h (%s) -->Finished. Rewrote 8 files. Don't forget to delete p.php.
有什么奇怪的,在我看来,它正试图做这样的事情test/test/p.php
而非test/p.php
。我认为这与它在达到该点时从较高的目录运行的事实有关。
任何人都知道我可以解决这个问题吗?
有什么理由不使用' sed'或其他更简单的linux工具? – 2011-12-22 15:36:56
@tandu,老实说我不知道'sed'是什么。除了我只是一名PHP程序员之外,没有其他理由。所以我去了PHP。别人真的不知道。 – Rob 2011-12-22 15:40:01