Php recursion causes insufficient memory
$ User = 'root'; $ pass = 'thrope'; $ dbh = new PDO ('MySQL: host = localhost; dbname = income ', $ user, $ pass ); $ query = 'Insert into picinfo set picpath =: pp, picsize =: PS '; // write the file path and file size to the database $ 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) // This recursive call is particularly resource consuming dir_read (realpath ($ dir. '/'. $ filename);} closedir ($ dh);} dir_read ('K:/project/fileoperate ');
The main function of the above code is to write all the files and subfolders in the K:/project/fileOperate directory into the database, however, this recursion is too resource-consuming and occupies more than 1 GB of memory.
I would like to ask where I have a problem? Or is there a better way?
Reply to discussion (solution)
I used a method provided by the xu moderator here.
$ Dir = 'd :\\';
$ Res = glob ($ dir );
For ($ I = 0; $ I
If (is_dir ($ res [$ I]) {
$ Res = array_merge ($ res, glob ($ res [$ I]. '/*');
$ G = glob ($ res [$ I]. '/*');
Var_dump ($ g );
}
}
?>
Why do you comment out if ($ filename = '.' | $ filename = '..') continue?
When $ filename = '.' and $ filename = '..', is_dir (realpath ($ dir. '/'. $ filename) is true. will no endless loops be generated?
Actually, using glob functions or directory iterators is much simpler.
Recursive memory consumption here should be a serious memory consumption for mysql insert operations. you can consider using load data infile to optimize it ..
If ($ filename = '.' | $ filename = '..') continue ;? Sentence is required? Yes, no ?? Dead cycle ?.
Processing with the SPL library provided by PHP is much faster: for example
$ Iterator = new \ RecursiveIteratorIterator (new RecursiveDirectoryIterator ('./'));
Foreach ($ iterator as $ it ){
Echo $ it-> getFilename (), '->', $ it-> getSize (),'
';
}
You can refer to the following manual, and SPL is well encapsulated.
Memory_get_peak_usage
I used this function to test the empty script and your code running on a GB D disk with all the fragmented files. The results are almost the same.
A little confused
1 GB is too scary. I suggest you try another method.
I feel that there is a problem with the LZ code. wow, we should add the current judgment to the parent directory, so there should be no such large memory usage.
If ($ filename = '.' | $ filename = '..') continue;
This must be added.