Skip to content

Instantly share code, notes, and snippets.

@azanebrain
Created January 19, 2014 20:18
Show Gist options
  • Save azanebrain/8510478 to your computer and use it in GitHub Desktop.
Save azanebrain/8510478 to your computer and use it in GitHub Desktop.
A PHP snippet that reads the files of a folder and returns the filename as an array
<?php
//vvvvvvvvvv *INCLUDE_FUNCTIONS vvvvvvvvvv
/* phpReadDir v0.1
* This function gets the contents of a directory.
* It returns an array ($contentsArr) of strings for each item in the target directory
* $dir : The path of the directory to search in
* Attributes:
ignoreSystemFiles: Do not include system files in the array
Such as: ., .., DS_Store
num: How many entries to return. 0 will return all
ignore: Ignore this file(s)
ignoreType: Ignore this file type(s)
*/
function phpReadDir($dir, $attributes){
// echo "get contents<br>";
$handle=@opendir($dir);
// echo " dir: $dir <br> handle: '$handle' <br>";
if($handle){
$contentsArr=array(); //this array holds the names of all the files in the target dir
$index=1; //How many times the loop has run
while ($entry = readdir($handle)) { //While there are files in the target dir
if($attributes['ignoreSystemFiles'] && $entry=="."
|| $attributes['ignoreSystemFiles'] && $entry==".."
|| $attributes['ignoreSystemFiles'] && $entry==".DS_Store"
|| $attributes['ignoreSystemFiles'] && $entry=="Thumbs.db"){
$index--; //Subtract from index so the right number of entries is returned
}//ignoreSystemFiles
else{
// echo "ELSE! array push '$entry'\n";
array_push($contentsArr, $entry); //Add the files to the array
}//push entry
$index++;
}//while
@closedir($handle);
return $contentsArr;
// echo "count: ".count($contentsArr)."\n";
}//if handle
@closedir($handle);
// echo "RETURNING:nothing <br>";
return;
}//phpReadDir
//Set the directory:
$dir = "../../".str_replace(get_bloginfo('siteurl')."/", "", $templateDirectory."/functions"); // take out the host to get just the path to the theme
//Need to add the '../../' to get to the root. If your siteurl is the same as your homeurl you will only need 1 '../'
//Create an array with each value of the dir
$functionsArr = phpReadDir($dir, array(
'ignoreSystemFiles' => true
));
//If there are files, include them:
if(@$functionsArr){
foreach($functionsArr as $function){
include('functions/'.$function);
}
}
//^^^^^^^^^^ /include_functions ^^^^^^^^^^
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment