Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HTML Directory Navigation 1

Status
Not open for further replies.

DLayzell

IS-IT--Management
Apr 27, 2005
29
CA
Good Day Fellow Tekkies,

I have a web project that I'm trying to complete on the double. I apologize if this is the wrong forum, but I'm using a multitude of languages, and thought this would get the most visibility.

My functional requirement is navigation of a directory of files (ie, lists of links to folders and files) in HTML. For example, I'd like to have the top-level directories listed as links, and following either link would "open" that folder, causing whatever files and subdirectories to be listed, also as HTML links, with the ability to navigate to the lowest-level directories.

My technical requirement is that it must work on a LAMP stack, that is, I'm coding in HTML/CSS/Javascript/PHP/SQL on an Apache/MySQL backend.

I've started by trying to upload a directory listing to a column of a SQL table, and I've been trying to use the right queries and PHP code to get functional navigation, but I've hit a wall. Here's my code for inspection:

HTML

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]
<?php include('../includes/php/suntime.php');?> <!-- Script to categorize server time -->
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
		<title>Portfolio - davidlayzell.com</title>
		<link rel="stylesheet" type="text/css" href="../includes/css/styles.css">
		<link rel="stylesheet" type="text/css" href="../includes/css/portstyles.css">
		<script src="../includes/js/menu_fader.js" type="text/javascript"></script>
		<!-- Script containing functions for showing resumes menu, and fading menu after idle period -->
		<script src="../includes/js/link_light.js" type="text/javascript"></script>
		<!-- Script containting functions to highlight links on rollover, and reset on mouseout -->
	</head>
	<body id="<?php echo($style); ?>"> <!-- Sets the body's ID to a server time category, showing different backgrounds -->		
		<div id="container">			
			<div id="side">				
				<script src="[URL unfurl="true"]http://widgets.twimg.com/j/2/widget.js"></script>[/URL]
				<script src="../includes/js/twitter_settings.js"></script>
				<!-- Script containing functions to embed an RSS feed of my twitter account. Twitter.com/dlayzell -->
			</div>
			<div id="main">
				<div id="inner">
					<a id="homelink" href="../"><div id="header">David Layzell's Portfolio</div></a>
					<div id="chron">
						<?php echo(date("l\, F dS\, Y h:i A")); ?> <!-- Command outputting current server date/time -->
					</div>
					<div id="formhead">Below, please find my portfolio, drawn from a directory of development and design work. Please note that your browser must have javascript enabled for this to function correctly.</div>
					<?php include('../includes/php/testlinks.php');?>
					<div id="menubar">
						<a href="../" onmouseover="set_fader(100);" alt="Home">Home</a> -
						<span id="resumewrap">
							<a href="../resumes/dev" onmouseover="show_resume_menu ();" alt="Resumes">Resumes</a> - 
							<span id="resumes" onmouseout="set_fader(100);">
								<a href="../resumes/dev" onmouseover="set_opacity();" onmouseout="set_fader(5000);" alt="Developer">Developer</a><br><hr>
								<a href="../resumes/sysadm" onmouseover="set_opacity();" onmouseout="set_fader(5000);" alt="Sys Admin">System Admin</a>
							</span>
						</span>												
						<a href="../testimonials" onmouseover="set_fader(100);" alt="Testimonials">Testimonials</a> -
						<a href="../projects" onmouseover="set_fader(100);" alt="Projects">Projects</a>	-
						<a href="../contact" onmouseover="set_fader(100);" alt="Contact">Contact</a>
					</div>					
					<div id="footer">Hosted by <a href="[URL unfurl="true"]http://www.bravenet.com/">Bravenet</a>[/URL] | Contact <a href="mailto:david[underscore]layzell[at]hotmail[dot]com?subject=Web Contact">Webmaster</a> | Copyright © David Layzell</div>
				</div>
			</div>			
		</div>
	</body>
</html>

PHP

Code:
<?php
	$sql_con = mysql_connect(localhost,root) or die('Could not connect: ' . mysql_error());
	mysql_select_db("davidlayzelldotcom", $sql_con);
	$sql_res = mysql_query("SELECT FILE_PATH FROM portfolio WHERE LOCATE('/',FILE_PATH,3) = 0") or die("Query failed with error: " . mysql_error());	
	$formhead = "<form id=\"portform\" name=\"portform\" action=\"./index.php\" method=\"GET\"><input type=\"hidden\" id=\"sub_check\" name=\"_submit_check\" value=\"0\">";
	$formfoot = "</form>";
	$pre_link = "<a onclick=\"document.['portform'].submit();return false\" id=\"portlink\"><div id=\"box\"";	
	$post_link = "</div></a>";
	$count = 1;
	echo $formhead;
	while($row = mysql_fetch_array($sql_res)){
		if ($count%2==0){$mid_link = $count . "\" class=\"evenlink\" onmouseover=\"highlight(this)\" onmouseout=\"reset(this)\">";}
		else {$mid_link = $count . "\" class=\"oddlink\" onmouseover=\"highlight(this)\" onmouseout=\"reset(this)\">";}
		$display = $pre_link . $mid_link . $row['FILE_PATH'] . $post_link;
		echo $display;
		$count++;
	}
	echo $formfoot;
	mysql_close($sql_con);
?>

I'm not so hung up on this work that I'm not willing to abandon it if I've completely overthought the problem. What I'd like for advice is either pointers on correcting my work above, or an altogether different direction to get the job done, hopefully with samples and/or tutorials.

Thanks for any input,

David Layzell, A+, Project+
Computer Network Engineering Grad
5 years SysAdmin, 11 years hobbyist Dev
 
I may be understanding this wrong, but if I'm not, I would not involve Mysql in the directory listings.

Using PHP's own opendir() and readdir() functions should suffice.

You can format the output as you deem necessary, making them links, icons, even thumbnails if you really needed too (though that is a little harder).

This approach also has the benefit that should the directory structure change for whatever reason (new directories, deletion of old ones, inclusion of more files etc..) the code would update the display automatically without any intervention from you.

Take this code out for a test run:
Code:
<?PHP

if(isset($_GET['dir']) && is_dir($_GET['dir'])){
$path=$_GET['dir'];
}
else{
$path="."; [green]/* Base Path to start listing */[/green]

}
if ($handle = opendir($path)) {
    
    while (false !== ($file = readdir($handle))) {
    if($file!='..'){   
     if(is_dir($file)){
	echo "<a href='dirlist.php?dir=$file'><b>$file</b></a>";
      }
	else{
     echo "<a href='$file'>$file</a>";
	}
    }
echo "<br>";    
}

  
    closedir($handle);
}
else{
echo "Error Opening Specified Directory: $path";
}


?>


This is very simple, but you can modify it to show folders first, add icons etc...

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Ohhhhh, yes!!

Phil, you are my hero; always pointing out the simple things I've missed. I THOUGHT there would be a php function for this, but my research failed, obviously.

Let me try this out! This might save me my from my mess of SQL, and javascript form handling bullswaddle.

David Layzell, A+, Project+
Computer Network Engineering Grad
5 years SysAdmin, 11 years hobbyist Dev
 
Alright, I've been pulled away from this project for awhile, but I've been playing with this again, and I've found an issue (maybe two) that I can't seem to get my head around. Here's the latest code:

Code:
if(isset($_GET['dir']) && is_dir($_GET['dir'])){$path=$_GET['dir'];}
	else{$path="./";}
	if ($handle = opendir($path)){		
		$count = 2;
		while (false != ($file = readdir($handle))) { 			
			if ($count%2==0){$class="evenlink";}
			else {$class="oddlink";}
			if($file != 'index.php' && $file != '.') {	
				if(is_dir($file)){
					$ref="index.php?dir=". $file;
				}
				else{$ref=$_GET['dir']. "/" . $file;}
				echo "<a href=\"" . $ref . "\" id=\"portlink\"><div id=\"box" . $count . "\" class=\"" . $class . "\" onmouseover=\"highlight(this);\" onmouseout=\"reset(this);\">" . $file . "</div></a>";
				$count++;
			}									
		}  
		closedir($handle);			
	}
	else{echo "Error Opening Specified Directory: $path";}

Now, the problem seems to be that readdir() is running in the context of the root directory, and it is failing to detect subdirectories as folders, and gives file links instead. (Actual file links work perfectly) Here's an example of what I mean.

A sample of my directory structure is like this:

>Root
---->Web (Link works)
-------->Programming (Link Works, but to ./Programming, NOT ./Web/Programming)
-------->Design (Link doesn't work)
---->Programming (Link works)
-------->Scripts (Link doesn't work)

This is the case, even if I manually load the $_GET['dir'] variable by the URL. Is there any way I can cause readdir() to work in the context of the current directory, or will it always work in the context of the parent directory?

David Layzell, A+, Project+
Computer Network Engineering Grad
5 years SysAdmin, 11 years hobbyist Dev
 
You'll need to keep sending the full path through the query string, so each time a folder is clicked the script knows where its located in the directory tree.

Otherwise you are sending a folder name that is not actually a valid directory form where the script is located, so the script defaults to "./"

Code:
if(isset($_GET['dir']) && is_dir($_GET['dir'])){$path=$_GET['dir'];}
    else{$path="./";}
    if ($handle = opendir($path)){        
        $count = 2;
        while (false != ($file = readdir($handle))) {             
            if ($count%2==0){$class="evenlink";}
            else {$class="oddlink";}
            if($file != 'index.php' && $file != '.') {    
                if(is_dir([red]$path."/".$file[/red])){
                    $ref="dirlist.php?dir=" . [red]$path . "/"[/red] . $file;
                }
                else{$ref=$path. "/" . $file;}
                echo "<a href=\"" . $ref . "\" id=\"portlink\"><div id=\"box" . $count . "\" class=\"" . $class . "\" onmouseover=\"highlight(this);\" onmouseout=\"reset(this);\">" . $file . "</div></a>";
                $count++;
            }                                    
        }  
        closedir($handle);            
    }
    else{echo "Error Opening Specified Directory: $path";
}

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
That's it! It's working perfectly now! Phil, I owe you a beer!
Starring every post. Thank you.

David Layzell, A+, Project+
Computer Network Engineering Grad
5 years SysAdmin, 11 years hobbyist Dev
 
Glad to be of help.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top