Page 1 of 1

php function calls

Posted: Mon Nov 08, 2010 7:25 am
by gsmith411
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.

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>";
}

?>
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

Re: php function calls

Posted: Mon Nov 08, 2010 7:44 am
by twinedev

Code: Select all

require_once('functions.php');
Note that in that file you still need to start it with the <?php opening tag.

see http://php.net/require_once

Re: php function calls

Posted: Mon Nov 08, 2010 8:14 am
by gsmith411
Perfect, that worked, the reference to the php doc also helped get the syntax correct.

Thank you