php递归罗致内存不够

WBOY
Release: 2016-06-13 12:02:10
Original
932 people have browsed it

php递归导致内存不够

<br />$user = 'root';<br />$pass = 'thrope';<br />$dbh = new PDO('mysql:host=localhost;dbname=income', $user, $pass);<br />$query = 'insert into picinfo set picpath=:pp, picsize=:ps';//把文件路径和文件大小写入数据库<br />$stmt = $dbh->prepare($query);<br /><br />function dir_read($dir){<br />	$dh = opendir($dir);//if (is_dir($dir)) echo realpath($dir).'<br/>';<br />	while (false !== ($filename = readdir($dh))){//echo realpath($dir.'/'.$filename).'<br/>';<br />		//if ($filename == '.' || $filename == '..') continue;<br />		if (is_file($dir.'/'.$filename)){<br />			global $stmt;<br />			$stmt->execute(array(':pp'=>realpath($dir.'/'.$filename), ':ps'=>filesize(realpath($dir.'/'.$filename))));<br />			//echo $dbh->errorCode();<br />		}<br />		if (is_dir(realpath($dir.'/'.$filename)))//这个递归调用特别耗费资源<br />			dir_read(realpath($dir.'/'.$filename));<br />		<br />	}<br />	closedir($dh);<br />}<br /><br />dir_read('K:/project/fileOperate');<br />
Copy after login

上面的代码主要功能是把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;
这个要加上。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!