我正在研究一個腳本,它用一個字符串替換目錄和子目錄中的所有文件,以擺脫我們的軟件顯示的通用錯誤消息。在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