Jump to content
xisto Community
itssami

How To Sort Files Of A Directory using Php

Recommended Posts

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.

              echo "<a href='$path/$file'>$file</a><br/>";
}
}



//closing the directory
closedir($dir_handle);

?> linenums:0'><?$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!

Edited by electriic ink (see edit history)

Share this post


Link to post
Share on other sites

haven't tested this but give it a try should work, create an array of the file names and then use the sort function.

<?$path = "";$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++;	}}sort($narray);for($i=0;i<sizeof($narray);$i++){	echo "<a href=".chr(34).$path."\".$narray[$i].chr(34).">".$file."</a><br/>";}//closing the directoryclosedir($dir_handle);?> 

Edited by mole2k9 (see edit history)

Share this post


Link to post
Share on other sites

So you want to display the files/folders in a directory alphabetically? The code is as follows:

<?$path = "";$files_gathered = array();$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 != '..') {   $files_gathered[] = $file;  }}//closing the directoryclosedir($dir_handle);// begin sorting and displaying the files $files_gathered = sort ($files_gathered); $count = count ($files_gathered); for ($loop_start = 0; isset($files_gathered[$loop_start]); $loopstart++) {  echo "<a href='" . $path . $files_gathered[$loop_start] . "' title="' . $files_gathered[$loop_start] . "'> " . $files_gathered[$loop_start] . " </a> <br />"; }  ?>

I haven't tested it yet but it should still work

Share this post


Link to post
Share on other sites

Both of those scripts look like they will work to sort in ascending order.To sort the array in descending order, use the function rsort() instead of sort(). Everything else should remain the same.

Share this post


Link to post
Share on other sites

Opps mean to use rsort also made 1 other change , chnage$sfile to $narray[$i] in,


echo "<a href=".chr(34).$path.$narray[$i].chr(34).">".$narray[$i]."</a><br/>";


this is tested and works,

<?$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);?>

you might want to add a function to check whether the path has a \ at the end and add one if not.
Edited by mole2k9 (see edit history)

Share this post


Link to post
Share on other sites

All it needs now is a form to select the directory and a radio button set to select ascending or descending sort order. Then an If statement to sort in the chosen order. And a set of html ul tags and li tags. And a class to hook the styling to for the html / css and you are all set.I prefer a single page script / form method personally.Looks good.

Share this post


Link to post
Share on other sites

i dont mean to bother but it still shows blank screen... for example i have a folder "test" in htdocs.. and i gave the path

$path = "test";
but it shows blank screen.. and if i give any wrong name of the folder which doesnt even exists in htdocs , it still shows blank page, even it should say "Unable to open ..."
im trying to find the problem but cant..

Opps mean to use rsort also made 1 other change , chnage$sfile to $narray[$i] in,echo "<a href=".chr(34).$path.$narray[$i].chr(34).">".$narray[$i]."</a><br/>";
this is tested and works,

<?$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);?>

you might want to add a function to check whether the path has a \ at the end and add one if not.

Share this post


Link to post
Share on other sites

Have a look at the script I sent to you and you will notice there is a line in in which sets the path to "./". This references the path which the script is run from. Modify this path to include the name of the directory on a relative basis.

$path = "./test/"

Also, if you are making changes to the script and want further advise, I would reccomend including a copy of the actual code which is not working. The sample you list above does not have any directory in it so I am curious about whether you actually have a valid path in the source code.

 

Also, the echo statement is commented out in the listing you display.

		//echo "<a href='$path/$file'>$file</a><br/>";
Check to make sure the commenting slashes are removed before running the script. With these slashes in place, the information is not being sent to the Browser. Might explain the blank page.

Share this post


Link to post
Share on other sites

thanks..i have edited a lil bit the above code..now it displays all the files and folders within a directory...but the problem is that , for example i have index.php file in that directory , it shows that index.php file also in the list..i want that it should show every file but NOT index.php.. what i should do for that ??

<?php$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($file != '.' && $file != '..')	{		//echo "<a href='$path/$file'>$file</a><br/>";		$narray[$i]=$file;		$i++;	}}sort($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);?>

Edited by itssami (see edit history)

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

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.??


<?php$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=".">" . $narray[$I] . "</a><br/>"; } }}closedir($dir_handle); //closing the directory?>

  thanks in advance


Share this post


Link to post
Share on other sites

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;//-$zitfunction 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";}?>

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | 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.