T
T
topalek2020-07-16 14:11:11
PHP
topalek, 2020-07-16 14:11:11

Why does the function write 2 times?

There is a folder with subfolders. In the final files are located, the links (paths) to which must be written to the file and this file must be in the final folder.
5f10336a31524470816153.png
There is a function that iterates through folders recursively and writes the paths to a file.

function build($dir) {
    foreach (scandir($dir) as $node) {
        if ($node == '.' || $node == '..') continue;
        if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) {
            build($dir .DIRECTORY_SEPARATOR . $node);
        } else {
            $dirname = dirname($dir . DIRECTORY_SEPARATOR . $node).DIRECTORY_SEPARATOR;
            if ($node !== "index.txt"){
                var_dump($dirname.$node);
                $idxFile = $dirname.'index.txt';
                file_put_contents($idxFile,  $dirname.$node. "\n",FILE_APPEND);
            }
        }
    }
}

In the code, you can see var_dump which dumps the current file path to the browser before writing it to the file.
The magic begins when this path is written to a file. The magic is that the paths are written twice.
Moreover, if there are several files in the folder, then the recording will go through each one first, and then again. Those. if it is in the folder 1.txt, 2.bat, 3.dll, then it will be written like this
1.txt
2.bat
3.dll
1.txt
2.bat
3.dll

and will be displayed in the browser once.

Question: how to fix it so that it is written to the file once?

Z.Y. through the console, the script works correctly and the recording goes one time

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AUser0, 2020-07-16
@AUser0

First, replace dirname()with realpath(). Secondly, move the second DIRECTORY_SEPARATOR inside the parentheses realpath(). And third, don't create new files in the directory you're reading from. Collect the output into a variable, and after scanning the directory (i.e. outside foreach (scandir($dir) as $node) {}) create a file in the scanned directory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question