Jump to content

[SOLVED] function goes into endless loop


qhiiyr

Recommended Posts

Hello, I'm trying to make a recursive function to search all subfolders for an index.php file and make one with this file's contents if there's not one there. But whenever I call the function, it sends the page into an infinite loop and I hit a maximum execution time error. This is the function:

 

<?php
function makeindex($start) {
foreach(glob($start . "/*") as $folder) {
	if(filetype($folder) == "dir") {
		if(!file_exists($folder . "/index.php")) {
			file_put_contents($folder . "/index.php", file_get_contents("index.php"));
		}
		makeindex($folder);
	}
}
}
?>

 

The main file's name itself is index.php, so with file_put_contents() I'm writing the contents of the index.php in the current directory (which can get a little confusing).

 

I'm calling the function with makeindex("").

 

Any help with this is greatly appreciated. Thanks!

Link to comment
https://forums.phpfreaks.com/topic/43514-solved-function-goes-into-endless-loop/
Share on other sites

That is not illegal as long as there is an escape. Marmite is right about calling itself inside itself is throwing the infinite loop.

 

Calling a function within a function is called Recursion and is used quite extensively. You just have to have the right code so it doesn't create an infinite loop.

 

http://en.wikipedia.org/wiki/Recursive

 

 

Yep, but it turns out I've got it figured out, thanks to a friend, and here's what he explained to me:

 

Every folder has two hidden links inside it. One, which you're probably aware of, is the ".." link (or more familiarly "../"), which goes up one folder. The other is ".", which goes to the folder itself. So my function is hitting the "." link every time and going into the same folder it was just in, which sends it into the infinite loop.

 

So the changed code looks like this:

 

<?php
function makeindex($start) {
foreach(glob($start . "/*") as $folder) {
	if(filetype($folder) == "dir" && $folder != ".") { // changed line
		if(!file_exists($folder . "/index.php")) {
			file_put_contents($folder . "/index.php", file_get_contents("index.php"));
		}
		makeindex($folder);
	}
}
}
?>

 

Thanks for your guys' help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.