Home
[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] Locate ISO Mount Points
by Chuck Kozler on Sep.27, 2009, under Home
I have seen some people coming through google looking for information to see where ISO’s get mounted to. So, I am writing this article (get more hits
). So, to understand this, there are two different ways that ISO’s can be mounted. If you do it through Nautilius’s Archive Mounter, you need to understand that it wont show up as an actual mount through mount -l. I don’t know why, but it doesnt.
Now, if the ISO was mounted (in my opinion, properly) through the command line and actually mounted with the iso9660 file system type selected as well as the loop option, then it will show up in mount’s list. To see mount’s list, just open a terminal and execute
sudo mount -l
If you would like to find out, more specifically, where maybe some ISO’s are mounted, you can try throwing grep in there.
sudo mount -l | grep -i iso9660
Will list all the mounts and only show you lines that contain iso9660. You may get /dev/sr1 that always shows up which I believe may be nautilus’s way of possibly virtually mounting the ISOs.
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( ); } }
[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
[PHP]Directory Listing v1 BETA
by Chuck Kozler on Jul.10, 2009, under Home, Programming
Hi everyone,
I hated the Apache and Lighttpd directory listings, so, I have made this. This was brought about because my roomates would always want to download some stuff from me, whether it was documents for projects, some song I was listening to, or a movie. With Apache and Lighttpd you are unable to download a whole directory but can download individual files. This seemed a little backwards to me since someone could easily traverse the directories themselves and download each file. Rather, this script will allow them click a button in a directory that will tar/rar the entire directory and then produce a download link for them.
This is currently in heavy beta, pretty much alpha, as the code below is going through heavy rewrites. Currently right now it:
1.) Caches all the files in the current directory
2.) Stores them in an array for indexing
3.) Sends a GET request with the ID (in the array) of the file
4.) When the user is at the do_download.php file, they are prompted with a download button to download the entire directory, or if they so choose, download an individual file
5.) If the user clicks the download button the script rar’s the entire directory and then produces a download link *Read Note*
6.) Once the rar/zip is complete, they are prompted with a download link
This currently has minimal security by only checking the ID and make sure it isnt out of bounds (too high or too low). I have provided the class of the directory listing as well as an example for an index.php page. The do_download.php is where the listing of the current directory is done as well providing the user a button to download the entire directory:
This is so alpha/beta that I am considering it more of a POC (proof-of-concept) for now until I have time to make it better and dynamic.
directory-list.class.php
<?php class dirlist { private $directory_path; private $folder_names = array( ); private $file_names = array( ); private $folder_full_paths = array( ); private $file_full_paths = array( ); private $dir_handle; function setDirHandle( $path ) { $this->dir_handle = opendir( $path ) or die( "Could not open directory." ); } function array_get_real_size( $array_in ) { $size = 0; if( sizeof( $array_in ) == 0 ) return 0; foreach( $array_in as $a ) { $size += sizeof( $a ); } return $size; } function print_array( $array_in ) { //All this does is echos pre tags and executes print_r. If I leave this here, my website breaks my code. } function getDirList( ) { $path = $this->directory_path; $this->setDirHandle( $path ); $dir_count = 0; $file_count = 0; while( false != ( $file = readdir( $this->dir_handle ) ) ) { if( $file == "." || $file == ".." ) continue; if( is_dir( $path . $file ) ) { $this->folder_names[ $dir_count ] = $file; $this->folder_full_paths[ $file ] = $path . $file; $dir_count++; } else { $this->file_names[ $file_count ] = $file; $this->file_full_paths[ $file ] = $path . $file; $file_count++; } } //$this->print_array( $this->file_full_paths ); //$this->print_array( $this->folder_full_paths ); return true; } function getFolderFp( $folder_name ) { return $this->folder_full_paths[ $folder_name ]; } function getFolderName( $index_number ) { return $this->folder_names[ $index_number ]; } function getTotalFolders( ) { return $this->array_get_real_size( $this->folder_full_paths ); } function getFileFp( $file_name ) { return $this->file_full_paths[ $file_name ]; } function getFileName( $index_number ) { return $this->file_names[ $index_number ]; } function getTotalFiles( ) { return $this->array_get_real_size( $this->file_full_paths ); } function getSortedFolderFp( $index_number ) { $sorted_folders = $this->folder_full_paths; sort( $sorted_folders, SORT_STRING ); return $sorted_folders[ $index_number ]; } function getSortedFolderName( $index_number ) { $sorted_folders = $this->folder_names; sort( $sorted_folders, SORT_STRING ); return $sorted_folders[ $index_number ]; } function getCurDir( ) { $tmp = $this->directory_path; $tmp_explode = explode( "/", $tmp ); $res = $tmp_explode[ sizeof( $tmp_explode ) - 2 ] . "/"; return $res; } function getCorrectedPath( ) { return $this->directory_path; } function correctPath( $path ) { $tmp = $path; $tmp_explode = explode( "/", $tmp ); $tmp_size = sizeof( $tmp_explode ); if( $tmp_explode[ $tmp_size - 1 ] == null ) { $this->directory_path = $path; return; } else { $this->directory_path = $path . "/"; return; } } function generateDownloadLink( $export_dir, $file_name ) { // make http://10.14.52.30/$dir->getcurdir()/$foldername $host = $_SERVER['SERVER_NAME']; $script_filename = basename( $_SERVER['SCRIPT_FILENAME'] ); $cur_path = preg_replace( '/'.$script_filename.'/','', $_SERVER['SCRIPT_NAME'] ); $link = "http://" . $host . $cur_path . $export_dir . $file_name; return $link; } function generateAHrefLink( ) { $host = $_SERVER['SERVER_NAME']; $script_filename = basename( $_SERVER['SCRIPT_FILENAME'] ); $cur_path = preg_replace( '/'.$script_filename.'/','', $_SERVER['SCRIPT_NAME'] ); $link = "http://" . $host . $cur_path; return $link; } function getPwd( ) { } function __construct( $path ) { $this->correctPath( $path ); } }; ?>
Index.php
<?php require_once( 'directory_list.class.php' ); $dir = new dirlist( "/var/www/music" ); $dir->getDirList( ); echo "<p align='left'>\n"; echo "<font size='+9' face='Verdana'>\n"; echo $dir->getCurDir() . "<br>\n"; echo "</font>\n"; echo "<font size='1' face='Sans MS'>\n"; echo $dir->getCorrectedPath( ) . "<br>\n"; echo "</font>\n"; echo "</p>\n"; echo "<font size='2'>\n"; for( $i = 0; $i < $dir->getTotalFolders( ); $i++ ) { $link = $dir->generateAHrefLink() . "do_download.php?id=" . $i; echo "   " . "<img src='http://10.14.52.30/images/folder.png'>" . "<a href='$link'>".$dir->getSortedFolderName($i)."</a><br>"; echo $link . "<br><br>"; } echo "</font>\n"; ?>
This needs heavy rewriting:
do_download.php
<?php $export_dir = "export/"; $export_dir_tmp = $export_dir; require_once( 'directory_list.class.php' ); function checkValidFileId( $id, $max_value, $min ) { // Out of bounds. Negative attempt or over max attempt if( ( $id < $min ) || ( $id > $max_value ) ) return false; else return true; } function getPwd( $in_path ) { $pwd = preg_replace( '/'.basename( $_SERVER['SCRIPT_FILENAME'] ).'/', '', $in_path ); return $pwd; } $dir = new dirlist( "/var/www/music" ); $dir->getDirList( ); $id = $_GET['id']; $pwd = getPwd( $_SERVER[ 'SCRIPT_FILENAME' ] ); $export_dir = $pwd . $export_dir; echo "<p align='left'>\n"; echo "<font size='+9' face='Verdana'>\n"; echo $dir->getCurDir() . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "</font>\n"; echo "<font size='1' face='Sans MS'>\n"; echo $dir->getCorrectedPath( ) . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "</font>\n"; echo "</p>\n"; echo "<font size='3' face='Times'>"; echo "You have requested the directory: <br>     " . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "<br>Click below to download<br>"; //- Create filename $filename = preg_replace( '/\s/', '_', $dir->getSortedFolderName( $id ) ); echo "</font>"; echo "<form action='" . basename( $_SERVER['SCRIPT_FILENAME'] ) . "?id=$id' method='post'>"; echo "<select name='format'>"; echo "<option value='zip'>Zip Archive</option>"; echo "<option value='rar'>Rar Archive</option>"; echo "<option value='tar'>Tar Archive</option>"; echo "<option value='gzip'>GZip Archive</option>"; echo "<input type='submit' name='Download' value='Download'>"; echo "</form>"; $inner_dir = new dirlist( $dir->getCorrectedPath( ) . $dir->getSortedFolderName( $id ) ); $inner_dir->getDirList( ); echo "Inner Path: " . $inner_dir->getCorrectedPath() . "<br>"; echo "Files: " . $inner_dir->getTotalFiles() . "<br>"; echo "<font face='Times' size='2'>"; for( $i = 0; $i < $inner_dir->getTotalFiles(); $i++ ) { echo "<a href='../../music/".$inner_dir->getCurDir() . $inner_dir->getFileName( $i )."'>".$inner_dir->getFileName($i)."</a><br>"; } for( $i = 0; $i < $inner_dir->getTotalFolders(); $i++ ) { echo "<a href='../../music/".$inner_dir->getCurDir() . $inner_dir->getFolderName( $i )."'>".$inner_dir->getFolderName($i)."</a><br>"; } echo "</font>"; if( $_POST['Download'] ) { switch( $_POST['format'] ) { case "zip": if( checkValidFileId( $id, $dir->getTotalFolders(), 0 ) ) { $export_filename = $filename . ".zip"; $export_fullpath = "\"".$export_dir . $export_filename."\""; $export_files_in = "\"".$dir->getSortedFolderFp( $id )."\""; $zip_executable = exec( 'which zip' ); $command = $zip_executable . " -r " . $export_fullpath . " " . $export_files_in; system( "echo Please wait while your file is processed" ); echo "<br>"; echo "<br>"; $export_fullpath = preg_replace( '/"/', '', $export_fullpath ); if( file_exists( $export_fullpath ) ) { //echo $dir->getHostPath() . "<br>"; echo "Your processing is complete: <a href='" . $dir->generateDownloadLink( $export_dir_tmp, $export_filename ). "'>$export_filename</a>"; exit; } if( is_writable( $export_dir ) ) { system( $command ) or die( "What" ); $export_fullpath = preg_replace( '/"/', '', $export_fullpath ); if( file_exists( $export_fullpath ) ) { echo "<br><br>"; echo "Your processing is complete: <a href='" . $dir->generateDownloadLink( $export_dir_tmp, $export_filename ). "'>$export_filename</a>"; exit; } } } else echo "You have tried to download an invalid file. Please try again." . "<br><br>"; break; case "rar": echo "We are rarring it" . "<br>"; break; case "tar": echo "We are tarring it" . "<br>"; break; case "gzip": echo "We are gzipping it" . "<br>"; break; default: break; } } //echo "Export dir: " . $export_dir . "<br>"; ?>
Some updates that will come:
A total of only three files needed: 1 for the class, 1 for the index, and 1 for the download. The next directory list class will traverse all of the directories from the current working path, recursively, allowing for a much wider dynamic behind this entire concept. So far, for me, doing this and keeping it organized is proving a little tricky.
Screenshots:
I am alive!
by Chuck Kozler on May.17, 2009, under Home
Hi everyone,
I just want to let everyone know that I am alive and well as is this website. I have a whole host of new things to post soon as a result of this project I have been working on over the past few months. I will be posting a ton of C#, PHP, and Bash Scripts that I wrote through out this project so, stay tuned!
Regards,
Chuck






