Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

How To Sort Files Of A Directory using Php


17 replies to this topic

#11 WindAndWater

    Advanced Member

  • Kontributors
  • PipPipPipPipPipPipPip
  • 106 posts

Posted 01 May 2006 - 10:21 PM

Change
if($file != '.' && $file != '..')
to
if($file != '.' && $file != '..' && file != 'index.php')


#12 BuffaloHelp

    Sterling Archer

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 4,088 posts
  • Gender:Male
  • myCENT:50.18

Posted 25 August 2006 - 04:30 AM

By the way you can write as

echo "<a href='$path$narray[$i]'>$narray[$i]</a><br/>";
and still be sufficient. As long as $path is correct you do not need char(34) since a single quote will suffice.

And when only one set of double quotes are used, no need to use periods to separate variables.

But the question I have is: how can I be able to hide the file extension? Is there a way or is it just too much?

---UPDATE---

Figured out how to replace

$filename = str_replace(".htm", ".", $narray[$i]);
OR

$filename = str_replace(".htm", "", $narray[$i]);
Place this right before echo (in my case) solved my issue. The problem was that the replacing string had to have a value. I left it as just " " and it wasn't working.

#13 iGuest

    Hail Caesar!

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 5,876 posts
  • Interests:Trap17 Free Web Hosting, No Ads

Posted 05 March 2009 - 05:21 PM

list files by extension from a directory with phpHow To Sort Files Of A Directory using Php

Thanks itssami, for your great code, I just need to add a little thing, I would like to restrict the list to the .Html files only, I mean, if I have a directory with let say .Html, .Txt and .Jpg files but I only want to list .Html ones, is there a way to do this?



#14 iGuest

    Hail Caesar!

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 5,876 posts
  • Interests:Trap17 Free Web Hosting, No Ads

Posted 15 November 2009 - 06:09 PM

 any chance to make this code to sort by date, or time so I can display the files in descending order from the oldest to the newest.??

 

<?$path = " ";$narray=array();$dir_handle = @opendir($path) or die("Unable to open $path");Echo "Directory Listing of $path<br/>";$I=0;While($file = readdir($dir_handle)){   if(is_dir($file))   {   continue;   }   else if($file != '.' && $file != '..')   {   //echo "<a href='$path/$file'>$file</a><br/>";   $narray[$I]=$file;   $I++;   }}Rsort($narray);

for($I=0; $I<sizeof($narray); $I++){Echo "<a href=".Chr(34).$path.$narray[$I].Chr(34).">".$narray[$I]."</a><br/>";

}

//closing the directoryClosedir($dir_handle);?>

 

thanks in advance



#15 Guest_Thomas V._*

  • Guests

Posted 12 May 2011 - 04:31 AM

How about some help cant figure out how to sort the Folders i can only sort files such as PDFs.



<?php
//$zit = 0;
//$zit = $zit + 1;
//-$zit
function ListFolder($path)
{

$pdfOrderarray=array(); 
    //using the opendir function
    $dir_handle = @opendir($path) or die("Unable to open $path");
    
    //Leave only the lastest folder name
    $dirname = end(explode("/", $path));
$i=0;    
    //display the target folder.
    echo ("<li><img alt='FOLDER' src='../../../images/Folder.png'> $dirname\n");
    echo "<ul>\n";

    while (false !== ($file = readdir($dir_handle))) 
    {
   if($file!="." && $file!="..")
        {
            if (is_dir($path."/".$file))
            {
                //Display a list of sub folders.
                ListFolder($path."/".$file);
            }
            else
            {
                //Display a list of files.
//                echo "<img alt='PDF' src='../images/PDF.png'> $file<br/>";
                $pdfOrderarray[$i]=$file; 
                $i++; 
           }
            
        }
   }

    //closing the directory
    closedir($dir_handle);
sort($pdfOrderarray); 
 
for($i=0; $i<sizeof($pdfOrderarray); $i++) 
{ 
echo "<img alt='PDF' src='../../../images/PDF.png'> $pdfOrderarray[$i]<br/>";
    } 

    echo "</ul>\n";
    echo "</li>\n";
}
?>




#16 jibberweed

    Newbie

  • Kontributors
  • Pip
  • 2 posts

Posted 12 May 2011 - 07:20 PM

Wondering if any one can help me out.
I can use the following script to display the files and folders but only the files are in alphabetical and not the folders, I know it will be using another array but cant seem to get it to work.
If you want a link to the sample page just ask me to send an email, Im sure the forum rules were i cant post a link to my site, but if im told its ok i will.

Im posting here because i used a little script from this Post to help with ording the files.

I attached a screen shot to show what im doing .

Thanks

<?php

function ListFolder($path)
{

$narray=array(); 
    //using the opendir function
    $dir_handle = @opendir($path) or die("Unable to open $path");
    
    //Leave only the lastest folder name
    $dirname = end(explode("/", $path));
$i=0;    
    //display the target folder.
    echo ("<li><img alt='PDF' src='../images/Folder.png'> $dirname\n");
    echo "<ul>\n";

    while (false !== ($file = readdir($dir_handle))) 
    {

   if($file!="." && $file!="..")
        {
            if (is_dir($path."/".$file))
            {
                //Display a list of sub folders.
                ListFolder($path."/".$file);
            }
            else
            {
                //Display a list of files.
//                echo "<img alt='PDF' src='../images/PDF.png'> $file<br/>";
                $narray[$i]=$file; 
                $i++; 
           }
            
        }
   }

    //closing the directory
    closedir($dir_handle);
sort($narray); 
 
for($i=0; $i<sizeof($narray); $i++) 
{ 
echo "<img alt='PDF' src='../images/PDF.png'> $narray[$i]<br/>";
} 
    echo "</ul>\n";
    echo "</li>\n";

}
?>

Attached Files


Edited by jibberweed, 12 May 2011 - 07:21 PM.


#17 jibberweed

    Newbie

  • Kontributors
  • Pip
  • 2 posts

Posted 12 May 2011 - 11:02 PM

I got it im giving complete code to allow even expandable file structure hope this helps someone besides my self.
as note i changed quite a bit.

if you want the java files just ask and i will send them to you

<?php

/* Rendering */ 
function list_dir($path) 
{ 
$items = get_sorted_entries($path); 

if (!$items) 
return; 


foreach($items as $item) 
{ 
if ($item->type=='dir') 
{ 
    echo ("<li><img alt='PDF' src='../../../images/Folder.png'>".$item->entry."\n");
    echo "<ul>\n";
list_dir($item->full_path); 
} 
else 
{ 
echo "<img alt='PDF' src='../../../images/PDF.png'> ".$item->entry."<br/>";
} 
} 

echo "</ul>"; 
echo "</li>\n";

} 

/* Finding */ 
function get_sorted_entries($path) 
{ 
$dir_handle = @opendir($path) ; 
$items = array(); 

while (false !== ($item = readdir($dir_handle))) 
{ 
$dir =$path.'/'.$item; 
if ( $item == '.' || $item =='..' ) 
continue; 

if(is_dir($dir)) 
{ 
$items[] = (object) array('type'=>'dir','entry'=>$item, 'full_path'=>$dir); 
} 
else 
{ 
$items[] = (object) array('type'=>'file','entry'=>$item, 'full_path'=>$dir); 
} 
} 
closedir($dir_handle); 

usort($items,'_sort_entries'); 

return $items; 
} 

/* Sorting */ 
function _sort_entries($a, $B) 
{ 
return strcmp($a->entry,$b->entry); 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
	<title>TITLE</title>
	
	<link rel="stylesheet" href="../jquery.treeview.css" />
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
	<script src="../lib/jquery.cookie.js" type="text/javascript"></script>
	<script src="../jquery.treeview.js" type="text/javascript"></script>
	
	<script type="text/javascript" src="demo.js"></script>
	
	</head>
	<body>
	
	<div id="treecontrol">
		<a title="Collapse the entire tree below" href="#"> Collapse All</a> | 
		<a title="Expand the entire tree below" href="#"> Expand All</a> | 
		<a title="Toggle the tree below, opening closed branches, closing open branches" href="#">
		Toggle All</a>
	</div>

<ul id="red" class="treeview-red">
<?php 
list_dir("directory you want to search"); 
?>
	</ul>


<hr />

 
</body></html>

Attached Files


Edited by jibberweed, 12 May 2011 - 11:03 PM.


#18 Guest_christopher-PH_*

  • Guests

Posted 09 December 2011 - 07:23 AM

View Postitssami, on 01 May 2006 - 11:30 AM, said:

The following code displays the files of folder...but they are displaced by the order of adding...
i want to sord the files / folders alphabetically and sord by accending order and by decending order..
can some one help me.

<?$path = "";$dir_handle = @opendir($path) or die("Unable to open $path");echo "Directory Listing of $path<br/>";while($file = readdir($dir_handle)) {	if(is_dir($file)) {		continue;		 }   else if($file != '.' && $file != '..') {			  echo "<a href='$path/$file'>$file</a><br/>";			}}//closing the directoryclosedir($dir_handle);?>

Notice from electriic ink:
Use
 tags for code!


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.

this is how to read folders and sub-folders and display them aphabetically

treeview(); // first.... call this function, change the parameter to change path (parameter is optional)




function treeview($path='.')
{
echo "<ul>";
recursive_read($path); //call recursion method to display folders and subfolders until it reach the bottom
echo "</ul>";
}

function recursive_read($path)
{
// open the path from parameter $path
$handle = opendir($path);

while($currentFile = readdir($handle) ){ // assign file names to $fileArray array
$fileArray[] = $currentFile;
}
closedir($handle); // close the handle;
asort($fileArray); // sort the folder alphabetically

// display main folders from directory using loop
foreach($fileArray as $file):
if($file != "." && $file != ".."){

$file = $path .'/'. $file;
$exp = explode('/', $file);
$file_name = end($exp);

if(is_dir($file)){ // check if the file is folder
echo "<li><span class='folder'>".$file_name."</span>";
if(!isEmptyDir($file)){
echo "<ul>";
recursive_read($file);
echo "</ul>";
}
echo "</li>";
}else{
// uncomment this to display non folder files
echo "<li><span class='file'>".$file_name."</span></li>";
}

}
endforeach;
}

function isEmptyDir($file){
return (($files = @scandir($file)) && count($files) <= 2);
}




Reply to this topic


This post will need approval from a moderator before this post is shown.

  


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users