Page 1 of 1

reading from multiple files in reverse order

Posted: Sat Oct 16, 2004 8:35 am
by andylyon87
I have a number of files in a folder, they are all created from a form that names them "time()" so they are all unique, the newest is laways assigned to the bottom of the folder, they are html files. How do I go about reading them in reverse order eg. newest to oldest. they will then be displayed in a page. (1-10) and then the next page will have (10-20)

The folder will be called logs

thanks
andy.

Posted: Sat Oct 16, 2004 12:25 pm
by kettle_drum
Get all the files in the directory into an array and then sort the array.

Code: Select all

$dir = "some/path";
$dp = opendir($dir);
while(false !== ($filename = readdir($dp))){
   $files[] = $filename;
}

rsort($files);

print_r($files);
Hopefully that will work.

Posted: Sat Oct 16, 2004 12:28 pm
by kettle_drum
Opps, you want closedir($dp); in there at the end :P

Posted: Sat Oct 16, 2004 6:34 pm
by m3mn0n
kettle_drum wrote:Opps, you want closedir($dp); in there at the end :P
(psst, you can edit your own posts after creation) :wink:

Posted: Sun Oct 17, 2004 6:35 am
by andylyon87
Does this allow me to read them say like in a bulletin board, i want the files to be read from in reverse order is there a way of getting tit to do this.

Posted: Sun Oct 17, 2004 6:46 am
by qads
The above code only reads the file names (all of them) into a array, after that you will need to read 10 files from the array and echo them, and put "back | next" links on ur page, something like:

Code: Select all

<?php
//get file names
$dir = "some/path";
$num = 10;
$start = (!isset($_GET['start'])) ? 0 : (int)$_GET['start'];
$dp = opendir($dir);
while(false !== ($filename = readdir($dp)))
{
$files[] = $filename;
}
rsort($files);
fclose($dp);

//read $num files
for($x = $start; $x < ($start + $num); $x++)
{
$file = $dir."/".$files[$x];
echo fread($file);
}
echo '<a href="page.php?start='.($start == 0) ? 0 : $start - $num.'">Back</a>';
echo '<a href="page.php?start='.($start + $num).'">NeXt</a>';
?>
untested...

You will still need to fix few things...i'll let you find what they are :twisted:

Posted: Mon Oct 18, 2004 11:28 am
by andylyon87
a bit harsh but thanks all the same :D

Posted: Mon Oct 18, 2004 4:42 pm
by qads
we can only show you the door, you gota open it your self :lol: