Smallish PHP/HTML Request

Jindo

Self
Reaction score
460
This is most likely a PHP job, but I have no idea what HTML is capable of these days...

---

I need a script that displays directories (not files) within the directory that the script is placed, and when a directory is clicked on, a list of directories and files within the directory appear, and the same for directories inside that directory etc. Also, if one directory is opened, all other directories (except any parent directories) are closed. Finally, I'd like it to remove any file-type suffixes on file names.

---

EXAMPLE: Below are three directories inside a root folder:

  • Directory 1
  • Directory 2
  • Directory 3

There are also files in the root, but I'd like not for them to show up unless inside one of the directories.

I want to view the contents of Directory 1, so I click on it:

  • Directory 1
  • Directory 1/File 1​
  • Directory 1/File 2​
  • Directory 2
  • Directory 3

The directory opens and the file paths become available (Doesn't display file-types).

Now I want to view Directory 2:

  • Directory 1
  • Directory 2
  • Directory 2a​
  • Directory 2/File 1​
  • Directory 2/File 2​
  • Directory 2/File 3​
  • Directory 3

Directory 1 automatically closes since Directory 2 is opened.

Now I want to open the directory inside Directory 2:

  • Directory 1
  • Directory 2
  • Directory 2a​
  • Directory 2a/File 1​
  • Directory 2/File 1​
  • Directory 2/File 2​
  • Directory 2/File 3​

Directory inside Directory 2 is opened.

---

If I've been unclear on anything in particular, please let me know.

Thanks in advance to anyone who is able to fulfill this request!
 

UndeadDragon

Super Moderator
Reaction score
447
I may be able to do this. I am just unsure of how to detect directories. Give me a bit of time and I will see if I can work it out.
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
Can PHP even do this?
HTML could work, but you would have to update it whenever something new is uploaded.
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
I may be able to do this. I am just unsure of how to detect directories. Give me a bit of time and I will see if I can work it out.

http://us2.php.net/manual/en/function.scandir.php

And for other directory functions:
http://us2.php.net/manual/en/book.dir.php

Can PHP even do this?
HTML could work, but you would have to update it whenever something new is uploaded.

Yes, PHP can do it easy. Dynamic is the way to go, HTML files are far too slow to update and make each time you upload a new file.
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
It doesn't take me that long to add a link to HTML...
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
True... Very true.
I was just thinking of alternitives.
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
Found this on the scandir page:

PHP:
<?php
function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
         if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
            }
    }
    return $dir_array;
}

$dirlist = getDirectoryTree('filmes','flv');
?>

With that function, all you would really have to do is echo out the data in a readable format, all the hard work is already done.
 

UndeadDragon

Super Moderator
Reaction score
447
PHP:
$dirlist = getDirectoryTree('filmes','flv');

What does the 'flv' parameter do?

EDIT: I think this (below) gives the best results. I just need to work out how to make it more readable:

PHP:
<?php

function rec_scandir($dir)
{
    $files = array();
    if ( $handle = opendir($dir) ) {
        while ( ($file = readdir($handle)) !== false ) {
            if ( $file != ".." && $file != "." ) {
                if ( is_dir($dir . "/" . $file) ) {
                    $files[$file] = rec_scandir($dir . "/" . $file);
                }else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
}

function cmp($a, $b)
{
    if ( is_string($a) && is_string($b) ) {
        return strcmp($a, $b) > 0 ? 1 : -1;
    }elseif ( is_int($a) && is_int($b) ) {
        return $a > $b ? 1 : -1;
    }elseif ( is_int($a) && is_string($b) ) {
        return 1;
    }elseif ( is_string($a) && is_int($b) ) {
        return -1;
    }else {
        return 0;
    }
}

function array_ukmultisort(&$arr, $func) {
    uksort($arr, $func);
    while ( list($key, $val) = each($arr) ) {
        if ( is_array($val) ) {
            array_ukmultisort($arr[$key], $func);
        }
    }
}

$dir = rec_scandir(".");
array_ukmultisort($dir, "cmp");
echo "<pre>";
print_r($dir);
echo "</pre>";

?>
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
PHP:
$dirlist = getDirectoryTree('filmes','flv');

What does the 'flv' parameter do?

From looking at it, I believe it's a way to show only certain filetypes, in this case those filetypes being Flash Videos (Flv).

This works fine for me:
PHP:
<?php

function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
         if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
            }
    }
    return $dir_array;
}

$dirlist = getDirectoryTree('thehelper', 0); 
print_r($dirlist);

?>
http://daikenkaiking.com/index2.php

All you would need to do is make a display for it.
 

Jindo

Self
Reaction score
460
It's a fair start, I really have little PHP knowledge so laying it out could be an issue as well (especially how I requested), but I'll see what I can do, thanks!
 

UndeadDragon

Super Moderator
Reaction score
447
The script I found does give some sort of structure, but it is still quite confusing (here).
 

Jindo

Self
Reaction score
460
The script I found does give some sort of structure, but it is still quite confusing (here).

That's very close to what I need, I also need the codes and array messages gone, for it to strip files of their file-type tags, and preferably only show files of a certain format.

Thanks for all the help so far guys.
 

TFlan

I could change this in my User CP.
Reaction score
64
PHP:
<?php
/* DDRtist's Function - Minorly tweaked */
function getDirectoryTree($outerDir){
    $dirs = array_diff(scandir($outerDir), Array(".", ".."));
    $dir_array = Array();
    foreach($dirs as $d){
        if(is_dir($outerDir."/".$d)){
            $dir_array[$d] = getDirectoryTree($outerDir."/".$d);
        }else{
            $dir_array[$d] = $d;
        }
    }
    return $dir_array;
}

/* Player 11's parser */
function parseTree($tree, $type){
    array_multisort($tree, SORT_DESC); // Sort so Folders > Files
    $return = ''; // Advoid "Notice's"
    $return .= '<ul style="list-style-type:none;list-style:none;">'; // Start the initial list
    foreach($tree as $a => $b){
        if(is_array($b)){
            $return .= '<li>- '.$a.'</li>'            // If it is a Directory; re-run the parser,
                    . parseTree($tree[$a], $type);    // grabbing all sub-folders / sub-files
        }else{
            $file = Array();  // Advoid "Notice's"
            $file = split("[/\\.]", $a); // Seperate file Extension and Name
            $show = false;  // Advoid "Notice's"
            $ext = count($file) - 1;
            foreach($type as $d){
                if($file[$ext]==$d){    // Test if file extension is desired,
                    $show = true;       // if it is, make it shown.
                }                       // If not, do nothing.
            }
            if($show){
                $return .= '<li>';                    // If file extension is desired,
                for($i=0;$i<(count($file)-1);$i++){   // make sure the entire filename
                    $return .= $file[$i];             // is included, since split() may
                }                                     // of created more array keys
                $return .= '</li>';                   // than desired
            }
        }
    }
    $return .= '</ul>'; // End list
    return $return;
}

// Call the parser with the root directory and file extensions desired
echo parseTree(getDirectoryTree('thehelper'), array('php', 'jpg', 'txt'));
?>

Using DDR's getDirectoryTree() function, I wrote a parser for you after adjusting a few things - messy, yes, but it works.

To use:
- Place in your file replacing "thehelper" with the root directory and "'php', 'jpg', 'txt'" with the file extensions you wish to be shown separated as shown.
PHP:
echo parseTree(getDirectoryTree('thehelper'), array('php', 'jpg', 'txt'));

I'm sure you can see where the HTML is implemented to style it, and if you need further help just ask.

EXAMPLE OUTPUT:
Code:
- includes
	mysql
	form
- images
	header
	footer
	background
- style
	- original
		- templates
		- images
			header
			background
	- css_files
index

EDIT (9.36pm EST 06.07.09)::
Just read your first post fully, I'll have that function added in a little bit (Opening / Closing of Dir's).
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
Well, I made a few new changes that are pretty sweet so far.

1. I made the folders collapsible and you click to open to see files. ( See preview link )
2. You can set the "type" param to 0 to display all files.
3. I made the CPU usage much less with checking if the filetype is allowed.
4. Added a few display things and two config options.

Note: You will need to upload the attached images inside the folder that $imgdir is set to ( default "imgs" ), and that folder must be inside the $dir folder ( default "thehelper" ). It won't show the folder or files inside the $imgdir folder.

Example link:
http://daikenkaiking.com/index2.php

PHP:
<?php

/* Config Options - DDRtists */
$dir = "thehelper";
$imgdir = "imgs";

echo '
<html>
<head>
<script language="javascript"> 
function toggle(divid) {
	var ele = document.getElementById(divid);
	if(ele.style.display == "block") 
	{
    	ele.style.display = "none";
  	} else {
		ele.style.display = "block";
	}
} 
</script>
</head>
<body>
';

/* DDRtist's Function - Minorly tweaked */
function getDirectoryTree($outerDir){
    $dirs = array_diff(scandir($outerDir), Array(".", ".."));
    $dir_array = array();
    foreach($dirs as $d){
        if(is_dir($outerDir."/".$d)){
            $dir_array[$d] = getDirectoryTree($outerDir."/".$d);
        }else{
            $dir_array[$d] = $d;
        }
    }
    return $dir_array;
}

/* Player 11's parser - Edited by DDRtists */
function parseTree($tree, $type){
	global $imgdir, $dir;
    array_multisort($tree, SORT_DESC); // Sort so Folders > Files
    $return = ''; // Advoid "Notice's"
    $return .= '<ul style="list-style-type:none;list-style:none;">'; // Start the initial list
	
    foreach($tree as $a => $b){
        if(is_array($b)){
			if($a != $imgdir)
            	$return .= '
						<li><img src="'.$dir.'/'.$imgdir.'/folder.gif" alt="" /><a href="javascript:toggle(\''.$a.'_div\')">'.$a.'</a></li>
						<div id="'.$a.'_div" style="display:none;">'            // If it is a Directory; re-run the parser,
                    	. parseTree($tree[$a], $type)
						.'</div>'; // grabbing all sub-folders / sub-files
        }else{
            $file = array();  // Advoid "Notice's"
            $file = split("[/\\.]", $a); // Seperate file Extension and Name
            $show = false;  // Advoid "Notice's"
            $ext = count($file) - 1;
			
			// Check if filetype is allowed or type is 0 - DDRtists
			if($type == 0 || in_array($file[$ext], $type))
				$show = true;
				
            if($show){
                $return .= '
				<li><img src="'.$dir.'/'.$imgdir.'/file.gif" alt="" />';                    // If file extension is desired,
                for($i=0;$i<(count($file)-1);$i++){   // make sure the entire filename
                    $return .= $file[$i];             // is included, since split() may
                }                                     // of created more array keys
                $return .= '</li>
				';                   			// than desired
            }
        }
    }
    $return .= '</ul>'; // End list
    return $return;
}

// Call the parser with the root directory and file extensions desired
echo parseTree(getDirectoryTree($dir), array('php', 'jpg', 'txt'));

echo '
</body>
</html>
';

?>

If I have time I'll do some visual things so it's more than text on a white screen. :p
 

Attachments

  • file.gif
    file.gif
    309 bytes · Views: 248
  • folder.gif
    folder.gif
    225 bytes · Views: 247

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
Now that I thought about it, I might be able to use something like this in my own server.
Will that support a CSS document? If so, what tags does it use (I can't read PHP at all), so I make make a stylesheet.
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
You can place any normal html in the echo that echos the head data or you could add more echos if you needed to echo other stuff.

Inside:
PHP:
echo '
<html>
<head>
<script language="javascript"> 
function toggle(divid) {
    var ele = document.getElementById(divid);
    if(ele.style.display == "block") 
    {
        ele.style.display = "none";
      } else {
        ele.style.display = "block";
    }
} 
</script>
</head>
<body>
';

can be treated as any normal header, so you could add in your header data there. Make sure that if it contains a ' character that you escape it with a \ like this: \'
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
Well, I've done all I'm going to do with it.
http://daikenkaiking.com/index2.php

Here it is, changes from last post:

A small config spot at the top of index.php. Change things as needed
A shitty css layout attempt
Code cleanup

I'll upload it with the images as a zip, if you need any help feel free to ask here.
 

Attachments

  • indexer.zip
    4.9 KB · Views: 178

TFlan

I could change this in my User CP.
Reaction score
64
DDRtist's I know you spent some time with the javascript and css, but here is what your after Jindo:

PHP:
<?php
$dir = 'thehelper';
$ext = array('php', 'jpg', 'html');
$hideOld = 'true'; // Hide previously opened folders

/* Dustin's getDirectroyTree() Function from 'http://us3.php.net/manual/en/function.scandir.php#88006' - Don't Edit */
function getDirectoryTree($outerDir){
    $dirs = array_diff(scandir($outerDir), Array(".", ".."));
    $dir_array = Array();
    foreach($dirs as $d){
        if(is_dir($outerDir."/".$d)){
            $dir_array[$d] = getDirectoryTree($outerDir."/".$d);
        }else{
            $dir_array[$d] = $d;
        }
    }
    return $dir_array;
}

/* Player 11's parser */
$dirs = Array();
$parents = Array();
function parseTree($tree, $type, $parent=''){
	global $dirs, $parents;
    array_multisort($tree, SORT_DESC); // Sort so Folders > Files
    $return = ''; // Advoid "Notice's"
    $return .= '<ul style="list-style-type:none;list-style:none;">'; // Start the initial list
    foreach($tree as $a => $b){
        if(is_array($b)){
			$multi = '';
			while(in_array('dir_'.$a.$multi, $dirs)){
    			$multi = rand(0, 100);
			}
			$dirs = array_merge($dirs, array('dir_'.$a.$multi));
            $return .= '<li class="dir" onclick="dirVis(\'dir_'.$a.$multi.'\')">- '.$a.'</li>'	// If it is a Directory; re-run the parser,
					 . '<span id="dir_'.$a.$multi.'" style="display:none;">' 		// grabbing all sub-folders / sub-files
                     . parseTree($tree[$a.$multi], $type, $a.$multi)
					 . '</span>';
			if(isset($parent)){				// Create the javascript variables needed
				$parents[$a.$multi] = $parent;
			}
        }else{
            $file = Array();
            $file = split("[/\\.]", $a); // Seperate file Extension and Name
            $show = false;
            $ext = count($file) - 1;
            foreach($type as $d){
                if($file[$ext]==$d){    // Test if file extension is
                    $show = true;       // desired, if it is, make it
                }                       // shown. If not, do nothing.
            }
            if($show){
                $return .= '<li>';                    // If file extension is desired,
                for($i=0;$i<(count($file)-1);$i++){   // make sure the entire filename
                    $return .= $file[$i];             // is included, since split() may
                }                                     // of created more array keys
                $return .= '</li>';                   // than desired
            }
        }
    }
    $return .= '</ul>'; // End list
    return $return;
}

// Call the parser with the directory and file extensions desired
$tree = parseTree(getDirectoryTree($dir), $ext);
?> 
<html>
<head>
	<title>Dir Listing</title>
    <style type="text/css">
		body {
			margin:0px;
			padding:0px;
			font:Verdana, Arial, Helvetica, sans-serif;
			font-size:14px;
		}
		li.dir {
			cursor:pointer;
			color:#0000FF;
		}
		li.dir:hover {
			cursor:pointer;
			color:#FF0000;
			text-decoration:underline;
		}
    </style>
    <script type="text/javascript">
		<?php
			echo 'var dirCount = '.count($dirs).';';
		?>
		function dirVis(id, parent){
			var dirListing = new Array();
			var parents = new Array();
			<?php
				echo 'var hideOld = '.$hideOld.';';
				for($i=0;$i<count($dirs);$i++){
					echo 'dirListing['.$i.'] = "'.$dirs[$i].'";';
				}
				
				foreach($parents as $a => $b){
					echo 'parents["dir_'.$a.'"] = "dir_'.$b.'";';
				}
			?>
			if(document.getElementById(id).style.display=="block"){
				document.getElementById(id).style.display = "none";
			}else{
				for(i=0;i<dirCount;i++){
					if(id != dirListing[i] && hideOld == true){
						document.getElementById(dirListing[i]).style.display = "none";
					}
				}
				document.getElementById(id).style.display = "block";
				var finalParent = parents[id];
				while(finalParent!=''){
					document.getElementById(finalParent).style.display = "block";
					finalParent = parents[finalParent];
				}
			}
		}
	</script>
</head>
<body>
<?php
// Display the Tree
echo $tree;
?>
</body>
</html>

What I added was what you specifically requested, you can now open / close folders - as DDR has made - but it also closes all the other ones, I placed a CSS stylesheet in there where you can modify the look and feel of the list. It's basic, but it's exactly what you asked for.

I do not have a live preview, but picture DDR's preview but with the closing of the other folders when you open a new one.

Hope this helps.
 

UndeadDragon

Super Moderator
Reaction score
447
You two beat me :p

Mine wasn't as good as either of them.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • The Helper The Helper:
    Actually I was just playing with having some kind of mention of the food forum and recipes on the main page to test and see if it would engage some of those people to post something. It is just weird to get so much traffic and no engagement
  • The Helper The Helper:
    So what it really is me trying to implement some kind of better site navigation not change the whole theme of the site
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top