php function calls
Posted: Mon Nov 08, 2010 7:25 am
I am a beginner at this php stuff, so appreciate all the help. I have a website with about 8 pages, each page has an identical php function, list all the files in a given directory, sorted to alphabetical order, then list them as links. Its all the same code, just called for a different file directory for each page. How can I write the code once, save it as a function, then call it from each page, sending it the directory I need the list of?
Here is the code I am using on each page.
There has to be a way to put function alpharead3 in its own file somewhere, maintain a single copy (much easier to make changes on one copy), then call it from each page, sending it the name of the directory I want the file list of and having it return the array. I tried getting an include statement working, but can't see how to pass it the directory I want to list.
Thank you
Here is the code I am using on each page.
Code: Select all
<?php
function alpharead3($dir){
if(!$dir){$dir = '.';}
foreach (glob("$dir/*") as $item){$sort[]= end(explode('/',$item));}
$killit = array('index.html', 'index.php', 'thumbs.db', 'styles.css');
$killcounter = 0;
foreach($sort as $sorteditem){
foreach($killit as $killcheck){
if(strtolower($sorteditem) == strtolower($killcheck))
{unset($sort[$killcounter]);}
}$killcounter++;}
if($sort){natsort($sort);}
foreach($sort as $item){$return[]= $item;}
if(!$return){return array();}
return $return;
}
//some basic usage
$folder = 'directory_one';
foreach(alpharead3($folder) as $item)
{
echo '<li><a href="' . $folder . '/' . $item . '">' . $item . '</a></li>';
//echo "<li><a href='" . $folder . "/" . $item . "'>" . $item . "</a></li>";
}
?>
Thank you