Script to add index.html to all directories recursively to avoid directory listing

Hi guys,

Have you caught in situation where you can’t use php.ini or .htaccess file to restrict directory listing, and only solution is to add index.html file to all directory ( In my case it was 379 )?

Well, I just caught in this situation today. Rather than going with manual way, I simply write one function which do it for me automatically and display message for each successfully created file. It also display message if there exist index.html file already in that directory and will keep it as it is in that case.

Rather wasting more time in description, here is the function. You just have to pass the path of directory and the function will add index.html file to all sub-directories of that particular directory. You can optionally pass string which the function will write in generated index.html file.

 * Add index.html file to all dir recursively starting from<br/>
 * give dir, this is extremely helpful when you want to<br/>
 * prevent directory indexing and don't want to add index.html<br/>
 * file to all directory manualy<br/>
 * Display message of success or failure
 * @author Neerav Dobaria < dobaria ##dot## dobaria ##at## >
 * @param string $dirPath Path of directory
 * @param string $string Optional String to write on file
 * @return void
function add_index_html($dirPath, $string = "") {
	$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath), RecursiveIteratorIterator::SELF_FIRST);

	foreach ($objects as $name => $object) {
		if (is_dir($object->getPathname()) AND FALSE === strpos($object->getPathname(), '.svn')) {
			$dirs[] = $object->getPathname();
	if ("" == $string) {
		$string = '<html>
	<title>403 Forbidden</title>

<p>Directory access is forbidden.</p>


	$length = strlen($string);

	foreach ($dirs as $dir) {
		$filename = $dir . DIRECTORY_SEPARATOR . 'index.html';
		if (!file_exists($filename)) {
			$fp = fopen($filename, 'w');
			fputs($fp, $string, $length);
			echo $message[] = '<span style="color:green;">' . $filename . ' added successfully<br/>';
		else {
			echo $message[] = '<span style="color:red;">' . $filename . ' already exist</span><br/>';


Hope it will save your time. If you have better solution that this or have any improvement in this script, fill free to submit comment. I would love to hear from you.

Tags: ,

No comments yet.

Leave a Reply

You must be logged in to post a comment.