Computers
[Linux/Shell/Bash] Count pattern matches/instances in string
by Chuck Kozler on Jan.20, 2010, under Computers, Linux/Unix, Networks/Servers, Programming, Web Dev
This handy little Bash scripting function will count the number of instances it finds in a string by the given delimeter. As of right now, its pretty basic…I didnt go too far into expanding it and working it (like going through and escaping all character escapes) and only escape for | and \.
function countPatterns { string_in="$1" delim="$2" if [ $delim == "/" ] || [ $delim == "|" ]; then delim="\\$delim"; fi retval=`echo $string_in | perl -ne 'while(/'${delim}'/g){++$count}; print "$count\n"'` return $retval }
Remember, this isnt really completed but you get the idea. The use is something like:
countPatterns "this|is|a|string|" "|" instances="$?" #would output 4 echo $instances
[VirtualBox/Linux/Windows] Copied Linux Guests Increasing eth devices
by Chuck Kozler on Jan.13, 2010, under Computers, Linux/Unix, Ubuntu, Windows
I noticed that when you copy Linux guests (VBoxManage clonevdi) and then try to use them, your ethernet device adapters keep increasing by one (eth0,eth1,eth2..etc).
This happens because the OS is looking in /etc/udev/rules.d/70-persistent-net.rules to look for the MAC address and corresponding adapter. Since the MAC address on the now new guest has been changed by VirtualBox, obviously the Guest OS can not find this MAC address. Naturally, it disables eth0 and creates eth1 with the new VirtualBox generated MAC address.
This can become quite troublesome, especially if you make a copy of a copy of a copy and so on.
I wrote a quick script to swap these MAC addresses around for you. I had to write something like this because I had to deploy about 20 Virtualized Guests and I created a base VDI to copy over and over as I needed it. I placed this script in the /root directory so I could just “su” and execute it, restart, and my address was fixed.
#!/bin/bash user=`whoami` if [ $user != "root" ]; then echo "You must be root to run this. Exiting." exit 300 fi function swapMacs { eth0_mac=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth0" | cut -d ',' -f4 | cut -d '=' -f3 | cut -d '"' -f2 | sed -e 's/:/\\\\:/g'` if [ -z $eth0_mac ]; then echo " ! MAC Address for eth0 is empty. Could not retrieve MAC from udev file." exit 100 fi eth1_mac=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth1" | cut -d ',' -f4 | cut -d '=' -f3 | cut -d '"' -f2 | sed -e 's/:/\\\\:/g'` if [ -z $eth1_mac ]; then echo " ! MAC Address for eth1 is empty. Could not retrieve MAC from udev file. ( Are you sure the line exists? )" exit 100 fi echo " * Find old mac: $eth0_mac" echo " * Replacing with: $eth1_mac" sed -i "s/$eth0_mac/$eth1_mac/g" /etc/udev/rules.d/70-persistent-net.rules if [ $? -eq 0 ]; then echo " + Successfully swapped mac addresses" echo " * Setting new udev file" new_rule=`cat /etc/udev/rules.d/70-persistent-net.rules | grep -i "eth0"` echo $new_rule > /etc/udev/rules.d/70-persistent-net.rules if [ $? -eq 0 ]; then echo " + We have successfully updated the udev file" else echo " ! Problem updating the udev file" exit 100 fi else echo " ! Problem swapping mac addresses" exit 100 fi } swapMacs
[PHP]Empty an array
by Chuck Kozler on Dec.20, 2009, under Computers, Home, Programming, Web Dev
This simple function will empty an array for you. I had to use this for some stuff I was writing for parsing the results of a MySQL query.
I am surprised that there isnt a built in PHP function for this. If there is, let me know…please!
<?php function emptyArray( $array ) { $size = sizeof( $array ); for( $i = 0; $i < $size; $i++ ) { array_pop( $array ); } } ?>
I would use this so that I could use the same array over and over again in a class and have it be dumped every execution of the function it was being utilized in.
Sphere: Related Content[Ubuntu/Linux] Set networking script
by Chuck Kozler on Dec.09, 2009, under Computers, Home, Linux/Unix, Networks/Servers, Ubuntu
Hi Everyone,
I have to manually change my network configuration settings a lot on my laptop when I’m at work and jumping between routers and other networks.
I got tired of manually entering all the commands so I wrote this. I expanded it a bit so other people can use it.
Its a quick and dirty script so it doesnt catch errors. Just checks if ifconfig and route commands were executed successfully.
Its pretty self explanitory. It takes in arguments of
device = the device you want to modify (eth0, eth1, etc…)
ip = the IP you want to set for yourself
gateway = The gateway you’re connecting to
dns = This is optional but you can set your own single DNS server address. If you do not enter one, the script will ask you if you want it to set you default ones with OpenDNS’ DNS server (http://opendns.org).
#!/bin/bash script_name=`basename $0` echo "" if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then echo "Usage is: " echo "" echo " $script_name [device] [ip_addr] [gateway] [Optional: one_dns_server]" echo "" echo "Note: Only one DNS server can be set. Manually update resolv.conf if you want more" echo "Note: If no DNS is specified, the script will ask you if you want it to set you one." echo "" echo "" echo "Example: " echo "" echo " $script_name eth0 192.168.1.135 192.168.1.1 4.2.2.2" echo "" exit 0 fi device="$1" ip="$2" gw="$3" primary_dns="$4" user=`echo $USER` ans='y' if [ $user != "root" ]; then echo "You must be root to run this" exit 108 fi if [ -z $device ]; then echo "You must specify a device to modify" exit 5 fi if [ -z $ip ]; then echo "You must specify an IP address for your machine" exit 5 fi if [ -z $gw ]; then echo "You must specify a default gateway address" exit 5 fi if [ -z $primary_dns ]; then echo "* No DNS server set." echo "* You do not need to specify a DNS server but it is suggested" echo "* Would you like the script to write default DNS for you (using OpenDNS)? [y/n] (default: y)" read ans echo "Write DNS = " $ans fi # Do the networking configuration # ifconfig eth0 $ip if [ $? -eq 0 ]; then success=1 fi route add default gw $gw ret="$?" if [ $ret -eq 0 ] || [ $ret -eq 7 ]; then success=2 fi if [ ! -z $primary_dns ]; then su -c "echo nameserver $primary_dns > /etc/resolv.conf" else if [ $ans == 'y' ] || [ $ans == 'Y' ]; then su -c "echo nameserver 208.67.222.222 > /etc/resolv.conf" su -c "echo nameserver 208.67.222.220 >> /etc/resolv.conf" fi fi device_ip=`ifconfig eth0 | grep -i $ip | cut -d ':' -f2 | cut -d ' ' -f1` route_gw=`route -n | grep -i 192.168.155.1 | awk '{ print $2 }'` route_flag=`route -n | grep -i 192.168.155.1 | awk '{ print $4 }'` if [ $success -eq 2 ]; then echo "" echo "* Success!" echo "" echo "* IP: $device_ip" echo "* Gateway: $route_gw ( $route_flag )" echo "" fi exit
[Gentoo] VirtualBox/VMWare Networking pcnet32
by Chuck Kozler on Oct.07, 2009, under Computers, Home, Linux/Unix, Networks/Servers
So, personally, I have never really had to install Gentoo in a Virtualized environment so normally my networking and everything has worked right out of the box from the basic kernel configurations selected when you run “make menuconfig”.
Unbeknown to me, that would not at all be the case when you virtualize Gentoo with VMWare or VirtualBox. As some of you may know, VMware and VirtualBox both use a pcnet32 driver/module to enable networking. Now, after a ton of googling and back and forth I finally figured out what you have to do.
When you execute “make menuconfig”
make menuconfigThen, when you’re prompted with the options, step through the menu as such
Device Drivers
|----------> Network Device Support
|---------------> [ * ] Ethernet (10 or 100mbit)
|--------->[ * ] AMD PCNet32 PCI Support
Make sure you press “Y” to include it rather than modularize it (unless you have an initrd.img setup and want/need to modularize it) so this way you dont have to worry about editing
/etc/modules.autoload.d/
or having to do anything else for that matter to get networking working with the virtualized network/ethernet adapters
Then
# make -j2 # cp /usr/src/linux/arch/x86/boot/bzImage /boot/kernel # reboot
[Ubuntu\Mono\Gnome] GtkMountISO Application Release
by Chuck Kozler on Sep.27, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu, Windows
So, I guess this is my actual first application release in about 4 years since I stopped writing cheats/hacks for Counter-Strike and Counter-Strike source. You can see the video of this in action below and underneath, a link to download it from. You can find all the information you need in the readme. Please, make sure you read the readme, it will save us all a lot of time. For whatever reason, I am going to post the flow chart I made for the bash installer script. Maybe *someone* can find it useful in the future.
Sphere: Related Content[Ubuntu/Gnome] Gtk ISO Mount Program
by Chuck Kozler on Sep.24, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu
This is a program I wrote to mount ISO’s under Linux. I wrote it in C# utilizing the Mono libraries. I must say, I love C# so much more now. The video is below and the unedited/uncleaned code is below the video. Hope you enjoy!
using System; using Gtk; using System.Diagnostics; using System.Text.RegularExpressions; public partial class MainWindow: Gtk.Window { string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); public int runCommand( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) { proc.WaitForExit( ); return proc.ExitCode; } else { return proc.ExitCode; } } return -1; } public void runCommand( string command, string args, bool wait, int milliseconds ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) if( milliseconds > 0 ) proc.WaitForExit( milliseconds ); else proc.WaitForExit( ); else proc.Close( ); } } public string getOutput( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start( ) ) { if( wait == true ) { proc.WaitForExit( ); string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } else { string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } } else return "Could not start process. Check process file name."; } public string getCommand( string command_name ) { return getOutput( "which", command_name, false ); } public void UpdateMountList( ) { runCommand( "sh", "-c \"mount -l | grep -i \"" + Users_Home + "/.GtkMountISO\" | cut -d ' ' -f3 > " + Users_Home + "/.GtkMountISO/mounts.current\"", true ); int ln_count = 0; string cur_line = ""; System.IO.StreamReader file = new System.IO.StreamReader( Users_Home + "/.GtkMountISO/mounts.current" ); while( ( cur_line = file.ReadLine( ) ) != null ) { CurrentMounts.AppendText( cur_line ); ln_count++; } file.Close( ); CurrentMounts.RemoveText( ln_count ); } public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); if( !( System.IO.Directory.Exists( Users_Home + "/.GtkMountISO" ) ) ) { //If hidden GtkMountISO folder does not exist, create dir string mkdir = getCommand( "mkdir" ); Console.WriteLine( "GtkMountISO folder does not exist. Creating." ); int retval = runCommand( mkdir, Users_Home + "/.GtkMountISO", true ); if( retval == 0 ) { Console.WriteLine( "Created directory for GtkMountISO" ); } } else { UpdateMountList( ); } } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { int rm_retval = runCommand( "rm", Users_Home + "/.GtkMountISO/mounts.current", true ); Console.WriteLine( "Del retval = " + rm_retval ); Application.Quit (); a.RetVal = true; } protected virtual void OnMountISOClicked (object sender, System.EventArgs e) { string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); try { /* * 1.) Get Filename */ //Get Full file name string ISO_Name = SelectISOButton.Filename.ToString( ); Regex r = new Regex( @"\s+" ); string ISO_Name_Regex = r.Replace( ISO_Name, @"\\ " ); //Split it based on slashes string[] ISO_Name_Parts = ISO_Name.Split( '/' ); //Get length to subtract one and get single file name int Parts_num = ISO_Name_Parts.Length; string ISO_Parsed_Name = ISO_Name_Parts[ Parts_num - 1 ]; //Split string again based on "." to get standalone file name with no extension string[] ISO_Strip_Extension = ISO_Parsed_Name.Split( '.' ); int ISO_Parsed_Num = ISO_Strip_Extension.Length; string ISO_Cleaned_Name = ISO_Strip_Extension[ ISO_Parsed_Num - 2 ]; string iso_extension = ISO_Strip_Extension[ ISO_Parsed_Num - 1 ]; Console.WriteLine( "Extension = " + iso_extension ); if( iso_extension.Equals( "iso" ) || iso_extension.Equals( "ISO" ) ) { Console.WriteLine( "Cleaned Name = " + ISO_Cleaned_Name ); /* * 2.) Make folder name @ /_USERS_HOME_DIR_/_FILE_NAME_ */ string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); Console.WriteLine( Users_Home ); string mkdir = getCommand( "mkdir" ); string make_dir_cmd = mkdir + " " + Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; Console.WriteLine( make_dir_cmd ); int make_dir = runCommand( mkdir, Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name, true ); string mount_point = Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; int zenity_retval = -1; if( make_dir != 0 ) { zenity_retval = runCommand( zenity, "--question --text=\"Folder exists. Would you like to mount anyway?\"", true ); Console.WriteLine( "Zenity reval = " + zenity_retval ); } if( ( make_dir == 0 ) || ( make_dir != 0 && zenity_retval == 0 ) ) { Console.WriteLine( "Folder created" ); /* * 3.) Execute "mount -t iso9660 _FULL_FILE_NAME_ /_USERS_HOME_DIR_/_FILE_NAME_ -o loop */ string gksudo = getCommand( "gksudo" ); string mount = getCommand( "mount" ); Console.WriteLine( "ISO_Name = " + ISO_Name ); Console.WriteLine( "Mount_Point = " + mount_point ); //Need to some how account for white space without corrupting the commands sent to the system... int retval = runCommand( gksudo, "\"" + mount + " -t iso9660 " + ISO_Name_Regex + " " + mount_point + " -o loop\"", true ); Console.WriteLine( " Mount Retval = " + retval ); if( retval == 0 || retval == 1 ) { //Success if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Success! && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"Success\" --text=\"Success!\n\n You can find the ISO mounted at " + mount_point + "\"", true, 0 ); string nautilus = getCommand( "nautilus" ); if( nautilus.Equals( "" ) ) return; else runCommand( nautilus, "\"" + mount_point + "\"", false, 0 ); } else if( retval == 7 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is the file an actual ISO? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is the file an actual ISO?\"", true, 0 ); } else if( retval == 32 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is there already something mounted there? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is there already something mounted there?\"", true, 0 ); } /* * 4.) Add to flat file database of mounted folders */ UpdateMountList( ); } } else { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File is not an ISO image && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"You must select an ISO image file\"", true, 0 ); } } catch( NullReferenceException nullexception ) { string error = nullexception.ToString( ); if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " You must select a file first && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Error Thrown: \n\n" + error + "\n\nYou must select a file first\"", true, 0 ); Console.WriteLine( error ); } } protected virtual void OnUnMountISOClicked (object sender, System.EventArgs e) { Console.WriteLine( "Unmounting " + CurrentMounts.ActiveText ); string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); string gksudo = getCommand( "gksudo" ); string umount = getCommand( "umount" ); string iso_to_unmount = CurrentMounts.ActiveText; int umount_retval = runCommand( gksudo, "\"" + umount + " -f " + iso_to_unmount + "\"", true ); Console.WriteLine( "Umount retval = " + umount_retval ); if( umount_retval == 0 ) { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File successfully unmounted && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"error\" --text=\"File successfully unmounted!\"", true, 0 ); } UpdateMountList( ); } }
[Ubuntu/Wine] Windows Installer Service Could Not Be Accessed
by Chuck Kozler on Aug.27, 2009, under Computers, Linux/Unix, Ubuntu
I have noticed running Wine version 1.1.28 and trying to install some programs and/or games returned the error
“The Windows Installer Service could not be accessed. This can occur if you are running Windows in safe mode, or if the Windows Installer is not correctly installed. Contact your support personnel for assistance.”
This is how I went about fixing it:
1.) Download “winetricks” from here => http://wiki.winehq.org/winetricks – more specifically, you can execute this command:
wget http://www.kegel.com/wine/winetricks
2.) Execute winetricks
sh winetricks3.) Scroll down until you see “msi2″ and put a check next to it. This will install the Microsoft Installer version 2.0 for wine.
4.) Execute the command “winecfg”
winecfg
5.) Scroll down until you see msi(native, builtin)
6.) Click it and click the “edit” button to the right
7.) Click the radio button next to “Builtin then Native”
For whatever reason, this fixed the above problem for me. If it doesnt for you, let me know what problems you encountered.
Sphere: Related Content[PHP]Sort Files by Modification Date
by Chuck Kozler on Aug.20, 2009, under Home, Programming
Hi everyone,
I have needed this for some time now to organize photos by the most recent added into a folder for a clients website. Ill just give the code and give you an example (explained example) as to how I used it.
First, the client has a folder with all the images and I wanted to display the most recent added picture as the display picture for the album as well as have them sorted by most recent added into the folder. So, we have a folder with all the images, in this case there were about 27 images in the folder.
First of all, with this code, you will need to have already traversed the folder and stored all the files in an array. Whether you use array_push or just store it in a C style fashion, either way works. You still need to have them stored in an array. Then, you will need a second array to store the output to it. Remember, this is following my example so I will include almost all the code that it took for me to accomplish this Lets have a look:
// Image files array $image_files = array( ); // Array to store the images that were sorted $image_sorted = array( ); // Read the extension of the file name passed function readExtension( $file ) { $extension = substr( $file, strrpos( $file, '.' ) + 1 ); return $extension; } // This may already exist but I was in a coding frenzy. Obviously, this checks if it is an image or not function isImage( $file ) { $extension = readExtension( $file ); $valid_images = array( "gif", "jpg", "jpeg", "png", "gif" ); for( $i = 0; $i < sizeof( $valid_images ); $i++ ) { if( $extension == $valid_images[ $i ] ) { return true; } } } // Traverse the directory and get all the images in that folder function getImagesInFolder( $dir ) { if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumbs.db" ) { if( !( is_dir( $dir . $file ) ) ) { $file_fp = $dir . $file; if( isImage( $file_fp ) ) array_push( $GLOBALS['image_files'], $file_fp ); } } } closedir( $handle ); } } //The brunt of the post. Explained below in more detail function sortByModDate( $array_in, &$array_out ) { for( $i = 0; $i < sizeof( $array_in ); $i++ ) { $time_stamp = date("G:i:s-d-m-y", filemtime( $array_in[ $i ] ) ); $array_out[ $array_in[ $i ] ] = $time_stamp; } arsort( $array_out, SORT_STRING ); $array_out = array_keys( $array_out ); if( $array_out[ 0 ] == "0" ) array_shift( $array_out ); unset( $array_in ); } // Get the sorted file by index number. This seems a bit redundant so you can modify as you see fit. function getSortedImageByIdx( $index_num ) { sortByModDate( $GLOBALS['image_files'], $GLOBALS['image_sorted'] ); return $GLOBALS[ '{image_sorted[ $index_num ]}' ]; }
Lets dissect code behind the basis of this post:
// $array_in = Array of all the files you want to sort // $array_out = Array to store the sorted files function sortByModDate( $array_in, &$array_out ) {
// Loop through all the inputted files array for( $i = 0; $i < sizeof( $array_in ); $i++ ) {
// Receive the time stamp $time_stamp = date("G:i:s-d-m-y", filemtime( $array_in[ $i ] ) );
// Store the time stamp in the $array_out array using the file name as a key // // NOTE: This had to be done this way since you can not have duplicate keys. // If you have a file edited at the EXACT same time as another file, that file // will therefore be dropped from the sorting $array_out[ $array_in[ $i ] ] = $time_stamp; }
// Sort and reverse the array based on the string. This allows for you to reference the // most recent file by accessing index array 0 arsort( $array_out, SORT_STRING );
// Break the keys from the above sorted array which allows us to access the sorted files // in a numerical sense (see example use below) $array_out = array_keys( $array_out );
// Couldnt really figure out why an extra iteration was being done but sometimes it will // create a zero index with a zero in it. This shifts the array and removes that zero if( $array_out[ 0 ] == "0" ) array_shift( $array_out );
// Free-up some resources unset( $array_in ); }
And here is an example use:
echo "Most recent file: " . getSortedImageByIdx( 0 ) . "<br>";
Also, this was originally in a class and I made some edits here during the post so some stuff may not be directly copy and paste. Adjust accordingly.
Sphere: Related Content[PHP]Directory Listing v1.1 Beta
by Chuck Kozler on Aug.07, 2009, under Home, Programming
Hi everyone,
This is the second version of the PHP Directory Listing that is posted directly beneath this one. This one is a little better and coded a lot better in my opinion. Though heavy code changes will come in the final versions to make sure everything is cleaned and secure, this one is definitely better than the last.
Some changes are:
1.) Removed the download rar/tar/zip functionality for now until I can figure out the best/cleanest way to implement it
2.) BIG: The directory listing is now completely recursive. What does this mean? This means that instead of having to copy an index.php file to every single directory that you want a directory list in, you just have to copy the first one and it will scan through all directories and store them in memory. You can see a screenshot below for more details.
3.) Images are now used more dynamically based on the file type. Supported file types are most movie and audio formats as well as archives and images.
I think that covers most of the changes.
The recursive directories function just implements programming recursion and calls the directory traversal function over and over again until its done reaching directories.
dir_list.class.php – The heart of the directory listing. You can see an example of how to use this on an index.php below
<?php class cDirList { public $path; public $debug; function debugPrint( $text ) { echo "// " . $text . "<br>"; } //All directories recursively from current working directory, full path location public $directories = array( ); //Directories in current working directory, full path location public $pwd_directories = array( ); //Files full path location public $files = array( ); public $file_types = array( "archive" => array( "7z", "zip", "rar", "tar", "gzip" ), "audio" => array( "mp3", "ogg", "wma", "flac", "aif", "ra" ), "video" => array( "avi", "wmv", "mpg", "mpeg", "asf", "mkv", "flv", "mov" ), "doc" => array( "doc", "docx", "log", "msg", "ods", "m3u" ), "code" => array( "cpp", "c", "sh", "py", "php" ), "image" => array( "jpg", "png", "jpeg", "gif" ), "program" => array( "exe" ) ); function getArraySize( $array ) { return sizeof( $array ); } function getFinalIndex( $array ) { return sizeof( $array ) - 1; } function getDirAtIndex( $dir_array, $idx ) { return $dir_array[ $idx ]; } function getDirIndex( $dir_array, $dir_name ) { return array_search( $dir_name, $dir_array ); } function printArray( $array ) { print_r( $array ); } function crawlDirectories( $dir ) { if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumb.db" ) { if( is_dir( $dir . $file ) ) { //Store directories in array $dir_fp = $dir . $file; array_push( $this->directories, $dir_fp ); //Recursion, duh! So simple.... $this->crawlDirectories( $dir . $file . "/" ); } } } closedir( $handle ); } } function getFoldersInCwd( $dir ) { $dir = $this->correctPath( $dir ); if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumb.db" ) { if( is_dir( $dir . $file ) ) { //Store directories in array $dir_fp = $dir . $file; array_push( $this->pwd_directories, $dir_fp ); } } } closedir( $handle ); } } function getFilesInFolder( $dir ) { $dir = $this->correctPath( $dir ); if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumbs.db" ) { if( !( is_dir( $dir . $file ) ) ) { $file_fp = $dir . $file; //$this->files[$index_num] = $file_fp; array_push( $this->files, $file_fp ); } } } closedir( $handle ); } } function getSingleName( $full_path ) { $full_path_explode = explode( "/", $full_path ); $full_path_final_idx = $this->getFinalIndex( $full_path_explode ); return $full_path_explode[ $full_path_final_idx ]; } function correctPath( $path ) { $path_explode = explode( "/", $path ); $path_final_idx = $this->getFinalIndex( $path_explode ); if( $path_explode[ $path_final_idx ] == null ) return $path; else { $path .= "/"; return $path; } } function getRelativePath( $path ) { $path = str_replace( $_SERVER['DOCUMENT_ROOT'], "", $path ); return $path; } function getFileType( $file ) { $type = substr( $file, strrpos( $file, '.' ) + 1 ); return $type; } function handleFileType( $file ) { $file = strtolower( $file ); $got_type = 0; $in_file_type = ""; foreach( $this->file_types as $type => $key ) { foreach( $key as $ext ) { //$this->debugPrint( "Extensions: " . $ext ); if( $this->getFileType( $file ) == $ext ) { $in_file_type = $type; $got_type = 1; } } if( $got_type > 0 ) break; } if( $in_file_type == "archive" ) return "<img src='images/archives.png'/>"; else if( $in_file_type == "image" ) return "<img src='images/images.png'/>"; else if( $in_file_type == "video" ) return "<img src='images/videos.png'/>"; else if( $in_file_type == "doc" ) return "<img src='images/docs.png'/>"; else if( $in_file_type == "code" ) return "<img src='images/code.png'/>"; else if( $in_file_type == "program" ) return "<img src='images/programs.png'/>"; else if( $in_file_type == "audio" ) return "<img src='images/audio.png'/>"; else if( $got_type == 0 && $in_file_type == "" ) return "<img src='images/unknown.gif' height='16px' width='16px'/>"; } function getScriptRootDir( ) { $script_name = explode( "/", $_SERVER['SCRIPT_NAME'] ); $filename = $script_name[ sizeof( $script_name )-1 ]; return str_replace( $filename, "", $_SERVER['SCRIPT_FILENAME'] ); } function __construct( ) { $this->path = $this->getScriptRootDir(); $this->crawlDirectories( $this->path ); sort( $this->directories ); sort( $this->pwd_directories ); } }; ?>
Index.php
<?php require_once( 'dir_list.php' ); $dirlist = new cDirList( ); $dir = $dirlist->getScriptRootDir(); $dirlist->getFoldersInCwd( $dir ); echo "<font size='9' face='Verdana'>" . $dirlist->getRelativePath( $dir ) . "</font><br>\n" . "<font size='1' face='Sans MS'>" . $dirlist->path . "</font><br>\n<br>\n"; if( $dirlist->getArraySize( $dirlist->directories ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->pwd_directories ); $i++ ) { echo "<img src='images/folders.png'/>" . "<font size='2'> " . "<a href='do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "'>" . $dirlist->getSingleName( $dirlist->pwd_directories[$i] ) . "</a><br>\n" . "</font>"; echo "      " . "<font size='1'>" . "http://" . $_SERVER['SERVER_NAME'] . "/do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "<br>\n" . "</font>"; } } else { echo "<img src='images/nothing.gif' />" . "<font size='2'>  " . "No folders found" . "</font>" . "<br>\n"; } $dirlist->getFilesInFolder( $dir ); if( $dirlist->getArraySize( $dirlist->files ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->files ); $i++ ) { echo $dirlist->handleFileType( $dirlist->getSingleName( $dirlist->files[ $i ] ) ) . "<font size='2'><a href='" . $dirlist->getRelativePath( $dir ) . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "'>" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "</a></font><br>\n"; } } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No files found" . "</font>" . "<br>\n"; } ?>
do_list.php – List the files and/or folders in the current directory
<?php require( 'dir_list.php' ); $dirlist = new cDirList( ); //Get directory name based on GET index name $index_number = $_GET['id']; $dir = $dirlist->getDirAtIndex( $dirlist->directories, $index_number ); $dirlist->getFoldersInCwd( $dir ); echo "<font size='9' face='Verdana'>" . $dirlist->getRelativePath( $dir ) . "</font><br>\n" . "<font size='1' face='Sans MS'>" . $dirlist->path . "</font><br>\n<br>\n"; function checkId( $id ) { if( $id < 0 || $id > $GLOBALS['dirlist']->getArraySize( $GLOBALS['dirlist']->directories ) ) return; } checkId( $index_number ); if( $dirlist->getArraySize( $dirlist->pwd_directories ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->pwd_directories ); $i++ ) { echo "<img src='images/folders.png'/>" . "<font size='2'> " . "<a href='do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "'>" . $dirlist->getSingleName( $dirlist->pwd_directories[$i] ) . "</a><br>\n" . "</font>"; echo "      " . "<font size='1'>" . "http://" . $_SERVER['SERVER_NAME'] . "/do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "<br>\n" . "</font>"; } echo "<br>\n"; } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No folders found" . "</font>" . "<br>\n<br>\n"; } $dirlist->getFilesInFolder( $dir ); if( $dirlist->getArraySize( $dirlist->files ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->files ); $i++ ) { echo $dirlist->handleFileType( $dirlist->getSingleName( $dirlist->files[ $i ] ) ) . "<font size='2'><a href='" . $dirlist->getRelativePath( $dir ) . "/" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "'>" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "</a></font><br>\n"; } } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No files found" . "</font>" . "<br>\n"; } ?>
You can see some screenshots below of it in use.
1st screenshot shows the directory listing from the first index page. As you can see the numbers skip increments rather than being 1 at a time, this is because it has hit folders that have folders inside of them and then increments the ID number based on the directories found. The second screenshot shows the difference of images between different types of files. The third screenshot shows folders inside of a folder and how they are incremented accordingly (see screenshot 1 as well). The fourth screenshot shows you another directory listing and also shows how the script can go very deep through files and traverse all directories from a root directory.
- Dir_List_new




