Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rating: Thread Rating: 6 votes, 5.00 average.
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 04-24-2010, 02:49 AM   PM User | #16
freemany
New to the CF scene

 
Join Date: Apr 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
freemany is an unknown quantity at this point
Smile Sort folders/files alphabetically with jQuery

Quote:
Originally Posted by Stephane3d View Post
Hi,

This script works pretty well except that the files list is not ordered. I'd like to sort it alphabetically. Any idea how to do that?

For example, I got this:

0012.jpg
0011.pdf
0024.pdf
0004.jpg
0018.pdf
0008.pdf

While I'd like to get this:

0004.jpg
0008.pdf
0011.pdf
0012.jpg
0018.pdf
0024.pdf

Thanks for any help.
Before sorting the listed files/directories alphabetically, I coverted the function into the way listing the files/directories in list(ul/li) manner instead of the current 'intent' one. I reckon the list way is the most proper way to list nested items. Here is the new function:

PHP Code:
function getDirectory$path '.'){      
    
    
$ignore = array( 'cgi-bin''.''..' );
    
// Directories to ignore when listing output. Many hosts
    // will deny PHP access to the cgi-bin.

    
$dh = @opendir$path );
    
// Open the directory to the handle $dh
    
    
while( false !== ( $file readdir$dh ) ) ){
    
// Loop through the directory
        
        
if( !in_array$file$ignore ) ){
        
// Check that this file is not to be ignored
            
            // Just to add spacing to the list, to better
            // show the directory tree.
            
            
if( is_dir"$path/$file" ) ){
            
// Its a directory, so we need to keep reading down...
            
                               
                //Add a class as selector for the jQuery sorting later.
                
echo "<li>$file<ul class='has-children'>"
                
getDirectory"$path/$file");
                
// Re-call this same function but on a new directory.
                // this is what makes function recursive.
                
echo "</li>";
            
            } else {
            
                echo 
"<li>$file</li>";
                
// Just print out the filename
            
            
}
            
            
        
        }
        
    
    
    }
    echo 
"</ul>";
    
closedir$dh );
    
// Close the directory handle

}
//Add a class as selector for the jQuery sorting later.
echo "<ul class='has-children'>";
getDirectory"." ); 
Then add the following jQuery codes to sort the lists:

Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {   
$('ul.has-children').each(function() {
	var $t=$(this);
	var Li=$t.find('>li').get();
	Li.sort(function(a, b) {
             var A = $(a).text().toUpperCase();
             var B = $(b).text().toUpperCase();
             if (A < B) return -1;    // changing to 1 to sort in DESC order...
             if (A > B) return 1;     // changing to -1 to sort in DESC order...
           return 0;
        });
	 $.each(Li,function(i,v) {
	      $t.append(v);
	  });
});
</script>
Have fun
freemany is offline   Reply With Quote
Old 06-07-2010, 11:59 PM   PM User | #17
sheba
New to the CF scene

 
Join Date: Jun 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
sheba is an unknown quantity at this point
Hi! I was looking for a code snippet for directory traversal and i found tours (i feel too lazy tonight to do it by myself)
I tested on linux and works ok, on windows ok except for long paths.

And I actually need to index some dirs and files that have a really deep dir structure.
It just freezes when the path is longer than 255...
Do you have any ideas on how i can traverse such a structure?
Thank you very much!
Any help is really appreciated!
sheba is offline   Reply With Quote
Old 06-21-2010, 06:12 AM   PM User | #18
xGIHavoc
New Coder

 
Join Date: Jan 2006
Posts: 73
Thanks: 2
Thanked 3 Times in 3 Posts
xGIHavoc is an unknown quantity at this point
I like (turtles) natcasesort($files);
xGIHavoc is offline   Reply With Quote
Old 06-22-2010, 10:39 AM   PM User | #19
Candan
New Coder

 
Join Date: Jun 2010
Location: The Netherlands
Posts: 52
Thanks: 0
Thanked 6 Times in 6 Posts
Candan is an unknown quantity at this point
To be honest, I don't really like the supressing of potentional errors( @opendir ).
I was actually creating an online file management system, and already had this coded. (Currently secured it by IP Access).

PHP Code:
<?php

    
if($_SERVER['REMOTE_ADDR'] != 'YOUR_IP') {
        
        die(
"Only the webmaster can access this page's content. Please go back and open another file.");
        
    } else {
    
        if(isset(
$_GET['dir'])) {
        
            if(
$_GET['dir'] == "www") {
    
                
$dir './';
            
            } else {
            
                
$dir $_GET['dir'];
            
            }
        
        } else {
        
            
$dir '.';
            
        } 
        
        if(
$dir != '.') {
            
$dirlist explode('/'$dir);
            
$back substr_replace($dir''strpos($dir'/'.end($dirlist)), strlen('/'.end($dirlist)));
            
            echo 
'<a href="./management.php?dir='.$back.'">< Go back</a><br /><br />';
        }
        
        
$dirlist = array();
        
$filelist = array();
        
$i 0;
        
        foreach(new 
DirectoryIterator($dir) as $file) {
            
            if((!
$file->isDot()) && ($file->getFilename() != basename($_SERVER['PHP_SELF']))) {
                
                if(
$file->isDir()) {
                
                    
$dirlist[$i]['dir'] = $dir;
                    
$dirlist[$i]['name'] = $file->GetFilename();
                    
$dirlist[$i]['type'] = $file->GetType();
                    
                } else {

                    
$filelist[$i]['dir'] = $dir;
                    
$filelist[$i]['name'] = $file->GetFilename();
                    
$filelist[$i]['type'] = $file->GetType();
                    
$filelist[$i]['size'] = $file->getSize();
                    
$filelist[$i]['lmod'] = $file->getMTime();
                
                }
                
                
$i++;
        
            }
        
        }        
        
        echo 
'<table border="1px">';
        echo 
'<tr>';
        echo 
'<th>File Name</th>';
        echo 
'<th>File Type</th>';
        echo 
'<th>File Size</th>';
        echo 
'<th>Last Modified</th>';
        echo 
'<th>Edit</th>';
        echo 
'<th>Delete</th>';
        echo 
'</tr>';
        
        
        foreach(
$dirlist as $dirs) {
            echo 
'<tr>';
            echo 
'<td><a href="./management.php?dir='.$dirs['dir'].'/'.$dirs['name'].'">'.$dirs['name'].'</a></td>';
            echo 
'<td>'.strtoupper($dirs['type']).'</td>';
            echo 
'<td>N/A</td>';
            echo 
'<td>N/A</td>';
            echo 
'<td><a href="./edit.php?file='.$dirs['dir'].'/'.$dirs['name'].'&is_dir=1">Edit</a></td>';
            echo 
'<td><a href="./delete.php?file='.$dirs['dir'].'/'.$dirs['name'].'&is_dir=1">Delete</a></td>';
            echo 
'</tr>';
        }
        
        foreach(
$filelist as $files) {
            echo 
'<tr>';
            echo 
'<td><a href="./management.php?dir='.$files['dir'].'/'.$files['name'].'">'.$files['name'].'</a></td>';
            echo 
'<td>'.strtoupper($files['type']).'</td>';
            
            if(
$files['size'] >= 1024 && $files['size'] < 1048576) {
                
                
$files['size'] = round(($files['size'] / 1024), 2);
                echo 
'<td>'.$files['size'].' kB</td>';
                
            } else if(
$files['size'] >= 1048576 && $files['size'] < 1073741824){
                
                
$files['size'] = round(($files['size'] / 1048576), 2);
                echo 
'<td>'.$files['size'].' mB</td>';
                
            } else if(
$files['size'] >= 1073741824) {
            
                
$files['size'] = round(($files['size'] / 1073741824), 2);
                echo 
'<td>'.$files['size'].' gB</td>';
            
            } else {
            
                echo 
'<td>'.$files['size'].' B</td>';
                
            }
            
            echo 
'<td>'.date("d/m/y H:i:s"$files['lmod']).'</td>';
            
            echo 
'<td><a href="./edit.php?file='.$files['dir'].'/'.$files['name'].'&is_dir=0">Edit</a></td>';
            echo 
'<td><a href="./delete.php?file='.$files['dir'].'/'.$files['name'].'&is_dir=0">Delete</a></td>';
            echo 
'</tr>';
        }
        
        
        echo 
'</table>';
        echo 
'<br /><br />';
        echo 
'<a href="./create.php?is_dir=1&dir='.$dir.'">Create a Directory</a> - <a href="./create.php?is_dir=0&dir='.$dir.'">Create a File</a>';
        
    }
    
?>
(Not going to give the other pages tho, I might release the full source when I've got it done).
{

How it eventually looks:
http://img716.imageshack.us/img716/521/managementr.png

}
(only thing that needs to be added that it takes you to the actual page, instead of trying to open it as a dir when you click a file)

Last edited by Candan; 06-22-2010 at 03:32 PM..
Candan is offline   Reply With Quote
Old 08-06-2010, 01:44 PM   PM User | #20
asimbaki
New to the CF scene

 
Join Date: Aug 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
asimbaki is an unknown quantity at this point
Easy go: No recursive, no sort, no dir reading

PHP Code:
# system call do recursive dir listing. assign listing to array and sort on each
# pass with foreach loop.
# once you have array you can go further as sorting & recursion done.

$rtv =  `ls -RAFr /home/web.symfony/`; // system call to start listing
$dir = array();

foreach( 
preg_split("/\n/"$rtv) as $line ) {
  if(
preg_match("/:$/"$line)) { // if directory
    
if($line && $current_path) { // after first pass
        
asort($dir[$current_path]); // cool & easy sort
      
}
    
$current_path preg_replace("/:$/"''$line); // discard : from the path
  
}else if ($line != '') {
    
$dir[$current_path][] = $line// listing of the previous pass
  
}
}

print_r($dir); 
asimbaki is offline   Reply With Quote
Old 08-31-2010, 03:26 AM   PM User | #21
freemany
New to the CF scene

 
Join Date: Apr 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
freemany is an unknown quantity at this point
Thumbs up Php way to do the sorting

Quote:
Originally Posted by freemany View Post
Before sorting the listed files/directories alphabetically, I coverted the function into the way listing the files/directories in list(ul/li) manner instead of the current 'intent' one. I reckon the list way is the most proper way to list nested items. Here is the new function:

PHP Code:
function getDirectory$path '.'){      
    
    
$ignore = array( 'cgi-bin''.''..' );
    
// Directories to ignore when listing output. Many hosts
    // will deny PHP access to the cgi-bin.

    
$dh = @opendir$path );
    
// Open the directory to the handle $dh
    
    
while( false !== ( $file readdir$dh ) ) ){
    
// Loop through the directory
        
        
if( !in_array$file$ignore ) ){
        
// Check that this file is not to be ignored
            
            // Just to add spacing to the list, to better
            // show the directory tree.
            
            
if( is_dir"$path/$file" ) ){
            
// Its a directory, so we need to keep reading down...
            
                               
                //Add a class as selector for the jQuery sorting later.
                
echo "<li>$file<ul class='has-children'>"
                
getDirectory"$path/$file");
                
// Re-call this same function but on a new directory.
                // this is what makes function recursive.
                
echo "</li>";
            
            } else {
            
                echo 
"<li>$file</li>";
                
// Just print out the filename
            
            
}
            
            
        
        }
        
    
    
    }
    echo 
"</ul>";
    
closedir$dh );
    
// Close the directory handle

}
//Add a class as selector for the jQuery sorting later.
echo "<ul class='has-children'>";
getDirectory"." ); 
Then add the following jQuery codes to sort the lists:

Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {   
$('ul.has-children').each(function() {
	var $t=$(this);
	var Li=$t.find('>li').get();
	Li.sort(function(a, b) {
             var A = $(a).text().toUpperCase();
             var B = $(b).text().toUpperCase();
             if (A < B) return -1;    // changing to 1 to sort in DESC order...
             if (A > B) return 1;     // changing to -1 to sort in DESC order...
           return 0;
        });
	 $.each(Li,function(i,v) {
	      $t.append(v);
	  });
});
</script>
Have fun
Here is the PHP way to do the same sorting as the above with jQuery:
PHP Code:
<?
$tree
=array();

function 
getDirectory$path '.'){      
    
    
$ignore = array( 'cgi-bin''.''..' );
    
// Directories to ignore when listing output. Many hosts
    // will deny PHP access to the cgi-bin.

    
$dh = @opendir$path );
    
// Open the directory to the handle $dh
    
    //Make counter
    
$j=0;
    
$temp=array();
        
    while( 
false !== ( $file readdir$dh ) ) ){
    
// Loop through the directory
        
        
if( !in_array$file$ignore ) ){
        
// Check that this file is not to be ignored
            
            // Feed with file name           
            
$temp[$j]['name']=$file;
            
            if( 
is_dir"$path/$file" ) ){
            
// Its a directory, so we need to keep reading down...    
               
$temp[$j]['children']=getDirectory"$path/$file");
            } 
       
        }
        
       
$j++; //counting
    
    
}
    return 
$temp;
   
    
closedir$dh );
    
// Close the directory handle

}//end of function

//Put the file directory system in an array first...
$tree=getDirectory("/your-dirtory/here");

$type='desc'//set sorting type 'desc' or 'asc'


//recursive function for sorting arrays
function getSort(&$temp) {
 global 
$type;

 switch (
$type) {
      case 
'desc':
      
rsort($temp);
      break;
      case 
'asc':
      
sort($temp);
      break;
}
     
 foreach(
$temp as &$t) {
   if(
is_array($t['children']))
                       
getSort($t['children']);
 }
//end of function

//Go through arrays again for sorting...now we have new sorted array $tree...     
getSort($tree);
?>
<pre>
<?
print_r
($tree);  // output 
?>
</pre>
Have funs
freemany is offline   Reply With Quote
Old 10-07-2010, 02:14 AM   PM User | #22
davehere
New to the CF scene

 
Join Date: Oct 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
davehere is an unknown quantity at this point
hello,
well for me this function make the error :
Warning: readdir() expects parameter 1 to be resource, boolean given
for
while (false !== ($file = readdir($dh))) {

any idea?

I must say I don't think it's a good practice to put html in your code, it's better to separate front presentation from back, so this function will be more logic to integrate to make others operations (of course it's not a big deal to modify)
davehere is offline   Reply With Quote
Old 10-07-2010, 02:24 AM   PM User | #23
davehere
New to the CF scene

 
Join Date: Oct 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
davehere is an unknown quantity at this point
ok it was a problem with directory which doesn't exist, the strnage is function doesn't stop and go to infinite recursive
another list function I found useful : http://www.webmaster-talk.com/php-fo...rectories.html
davehere is offline   Reply With Quote
Old 08-25-2011, 11:56 AM   PM User | #24
abby99
New to the CF scene

 
Join Date: Aug 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
abby99 is an unknown quantity at this point
I just want to say thank you for the information.
It is very valuable for me..newbie here and encountering the same situation.
Thanks and keep up the good work..
abby99 is offline   Reply With Quote
Old 01-27-2012, 10:36 AM   PM User | #25
Dieter Gribnitz
New to the CF scene

 
Join Date: Jan 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Dieter Gribnitz is an unknown quantity at this point
dir to array recursive

The functions on this site did not work for me.
I wrote one myself.
It converts the directory structure into an array.
It returns some relevant data in the {data} key and loops through the rest.
It might not be the cleanest script but it does the job for me.
Maybe it helps someone.

PHP Code:
  //$include overrides $exclude. $include should be an array of file extensions eg. array("jpg", "png", "gif")
  
function readDirectory($path="./"$exclude=array("."".."".htaccess"), $include=false){
    
$ds "/";
    if(!
$path){ $path=$this->path;}
    
$return = array();
    
$return['{data}']['path'] = $path;
    
$return['{data}']['has_files'] = 0;
    
$return['{data}']['has_dirs'] = 0;
    
    if(
is_dir($path)){
      
$dir opendir($path);
      while (
$file readdir($dir)) {
        
        if(
is_dir($path.$ds.$file)){
          if(
$file != "." && $file != ".."){
            
$return[$file] = array();
          }
        } else { 
          if(!
$include){
            if(!
in_array($file$exclude)){
              
$return['{data}']['files'][] = $file;
              
$return['{data}']['has_files'] = 1;
            }
          } else {
            
$ext end(explode("."$file));//GET FILE EXTENSION
            
if(in_array($ext$include)){
              
$return['{data}']['files'][] = $file;
              
$return['{data}']['has_files'] = 1;
            }
          }
        }
        
      }
    }
    if(
is_array($return)){
      
      
ksort($return);
      if(isset(
$return['{data}']['files'])){
        
natcasesort($return['{data}']['files']);//SORT CASE INSENSETIVE
        
$return['{data}']['files'] = array_values($return['{data}']['files']);//REINDEX KEYS
      
}
      foreach(
$return as $key => $value){
        if(
is_array($value)){
          if(
$key != '{data}'){
            
$return['{data}']['has_dirs'] = 1;
            
$return[$key] = readDirectory($path.$key.$ds$exclude$include);
          }
        }
      }
    }
    return 
$return;
  } 
Dieter Gribnitz is offline   Reply With Quote
Old 06-19-2012, 05:13 AM   PM User | #26
clickonce
New to the CF scene

 
Join Date: Jun 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
clickonce is an unknown quantity at this point
thank for your code. but i want to call getDirectory() function with parameter like below example:
getDirectory("http://updatesofts.com");
does it work?
if not how to i can?
thanks.
clickonce is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:42 PM.


Advertisement
Log in to turn off these ads.