Getting the list of files in a folder

September 26th, 2008 by algis

Here is a nice recursive function that returns the list of files in a folder. If the folder contains subfolders, it will return the names with their relative path. Optionally you can supply a file type (extension) which you would like to consider, for example, return only .jpg or .php files.

function getDirListing( $dirName, $ext = '.php' ){
	$dirLising = array();

	$files = array();
	$dirs = array();

	if ! ( $handle = opendir($dirName) )
		return $dirLising;

	// read the folder file list
	while ( false !== ($f = readdir($handle)) ){
		// skip the dot pseudo folders
		if( substr($f, 0, 1) == '.' )
			continue;

		// check if it is our extension
		$thisExt = substr( $f, -strlen($ext) );
		if ( ($ext == $thisExt) && ($f != basename(__FILE__)) )
			$files[] = $f;

		// subfolder? save for later recursive call
		if( is_dir( $dirName . '/' . $f ) )
			$dirs[] = $f;
		}
	closedir($handle);

	$dirLising = $files;
	// now go through subfolders if any
	reset( $dirs );
	foreach( $dirs as $d ){
		$childListing = getDirListing( $dirName . '/' . $d );
		foreach( $childListing as $childFile )
			$dirLising[] = $d . '/' . $childFile;
		}

	sort( $dirLising );
	return $dirLising;
	}

Posted in PHP Application Development | Comments Off

Generating random strings - passwords, ref codes etc

September 19th, 2008 by algis

Often I need to generate a random string for a password, a ref code or something. So I have made this little PHP class. It is configured to use caps and digits.

For example, if you need to make up a reference number, something like H7-UE4-3GG, here is the sample code:

$gen = new aaRandomPasswordGenerator;
$gen->useLetters = false;
$gen->useCaps = true;
$gen->useDigits = true;

$components = array();
$components[] = $gen->generate( 2 );
$components[] = $gen->generate( 3 );
$components[] = $gen->generate( 3 );

$refno = join( '-', $components );

Class code:

class aaRandomPasswordGenerator {
	var $useLetters;
	var $useCaps;
	var $useDigits;

	function aaRandomPasswordGenerator(){
		$this->lettersSalt = 'abcdefghijklmnopqrstuvxyz';
		$this->capsSalt = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
		$this->digitsSalt = '0123456789';

		$this->useLetters = true;
		$this->useCaps = true;
		$this->useDigits = true;
		}

	function generate( $len ){
		$salt = '';
		if( $this->useLetters )
			$salt .= $this->lettersSalt;
		if( $this->useDigits )
			$salt .= $this->digitsSalt;
		if( $this->useCaps )
			$salt .= $this->capsSalt;

		srand( (double) microtime() * 1000000 );
		$pass = '';
		$i = 1;
		while ( $i <= $len ){
			$num = rand() % strlen($salt);
			$tmp = substr($salt, $num, 1);
			$pass .= $tmp;
			$i++;
			}

		return $pass;
		}
	}

Posted in PHP Application Development | Comments Off