php遞迴羅致記憶體不夠

來源:互聯網
上載者:User
php遞迴導致記憶體不夠

$user = 'root';
$pass = 'thrope';
$dbh = new PDO('mysql:host=localhost;dbname=income', $user, $pass);
$query = 'insert into picinfo set picpath=:pp, picsize=:ps';//把檔案路徑和檔案大小寫入資料庫
$stmt = $dbh->prepare($query);

function dir_read($dir){
$dh = opendir($dir);//if (is_dir($dir)) echo realpath($dir).'
';
while (false !== ($filename = readdir($dh))){//echo realpath($dir.'/'.$filename).'
';
//if ($filename == '.' || $filename == '..') continue;
if (is_file($dir.'/'.$filename)){
global $stmt;
$stmt->execute(array(':pp'=>realpath($dir.'/'.$filename), ':ps'=>filesize(realpath($dir.'/'.$filename))));
//echo $dbh->errorCode();
}
if (is_dir(realpath($dir.'/'.$filename)))//這個遞迴調用特別耗費資源
dir_read(realpath($dir.'/'.$filename));

}
closedir($dh);
}

dir_read('K:/project/fileOperate');

上面的代碼主要功能是把K:/project/fileOperate這個目錄下所有的檔案和子檔案夾下所有的檔案名稱和檔案大小寫入資料庫中,但是這個遞迴太耗費資源了,佔用了超過1G記憶體
我想請教是我什麼地方做得有問題?或者有更好的方法?
------解決方案--------------------
之前xu版主的一個方法在這裡借用一下
$dir='d:\\';
$res=glob($dir);
for($i=0;$iif(is_dir($res[$i])){
$res=array_merge($res,glob($res[$i].'/*'));
$g=glob($res[$i].'/*');
var_dump($g);
}
}
?>
------解決方案--------------------
你 為什麼把 if ($filename == '.'
------解決方案--------------------
$filename == '..') continue; 注釋掉?

當 $filename = '.' 和 $filename = '..' 時,is_dir(realpath($dir.'/'.$filename) 成立,不就產生死迴圈了嗎?

其實用 glob 函數 或 目錄迭代器要簡單的多
------解決方案--------------------
if ($filename == '.'
------解決方案--------------------
$filename == '..') continue;
這個要加上。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.