javascriptphphtmlserver-side

Linking to next HTML file in date-ordered directory


I have a website part of which contains the records for a club. Each day's records are stored in their own file with the format yyyymmdd.php (I use PHP includes to cut down on the amount of repeated code).

Each records page has a link to the previous day, the index, and the next day. Is there some code I can write to have the previous and next day links automatically go to the previous and next dated files in the directory, rather than having to put the filenames in manually? Something like:

<a href=*automatic link to previous day*>Previous</a>

and the same for the next day, rather than:

<a href="20240427.php">Previous</a>.

Not every day has its own record, so it's not as simple as simply cycling back or forward through the calendar.

I have tried using the code for answer 1 to this question.

However, while it works for the first page in the directory, subsequent pages act as if they ARE still the first page: the $currentIdx remains at 0 and the 'Next Day' link always links to the second day, not the third, fourth, fifth etc.


Solution

  • I figured out an answer to my own question. Instead of using the linked answer to create my array I used scandir(). My code is as follows:

    $dirPath = '/path/';
    $dir = $_SERVER['DOCUMENT_ROOT'].$dirPath;
    $fileList = scandir($dir);
    $currPage = $_SERVER['REQUEST_URI'];
    $currFile = substr($currPage, -12);
    $numFiles = count($fileList);
    $arrIdx = 0;
    
    for($i = 0; $i < $numFiles; $i++)
    {
        if($fileList[$i] == $currFile)
        {
            $arrIdx = $i;
        }
    }
    
    $nextFile = $dirPath;
    $nextFileIdx = $arrIdx + 1;
    
    if($arrIdx < $numFiles)
    {
        $nextFile .= $fileList[$nextFileIdx];
        echo '<a class="nodecs" style="margin-left: 20px" href="'.$nextFile.'"><span class="ghost-button">Next Day</span></a>';
    }
    else
    {
        echo '<span class="ghost-button">No Next Day</span>';
    }
    

    I also derived a slightly adjusted version to have links for 'previous day' on each page too.