Search code examples
phpnavigationglobslice

Automatically creating next and previous type pages using glob


Trying to make it so that the glob function displays only the first 10 results (text files from a folder) and then automatically the next 10 with a next button.

Currently, I used array_slice to display only the first 10, but I'm not sure how to automate the process.

foreach(array_slice(glob("*.txt"),0,9) as $filename) {
   include($filename); }

Oh and while I'm at it, if possible, display something like "displaying 1-10" and last/first links. I could probably figure that out myself after I get past the first obstacle, so don't bother with this unless it's a super easy solution.


Solution

  • What you're trying to accomplish is called pagination. From your example, you can dynamically choose which ten you're viewing by setting a variable that determines what number (file) to start at.

    Example:

    <?php
    $start = isset( $_GET['start']) ? intval( $_GET['start']) : 0;
    
    $glob_result = glob("*.txt");
    $num_results = count( $glob_result);
    
    // Check to make sure the $start value makes sense
    if( $start > $num_results)
    { 
        $start = 0;
    }
    
    foreach( array_slice( $glob_result, $start, 9) as $filename) 
    {
         include( $filename); // Warning!
    }
    

    If you only want to do increments of 10, you can add a check to make sure $start is divisible by 10, something like this after $start is retrieved from the $_GET array:

    $start = ( $start % 10 == 0) ? $start : 0;
    

    Now, for links, all you need to do is output <a> tags that have the start parameter set correctly. You will have to do some logic to calculate the next and previous values correctly, but here is a simple example:

    $new_start = $start + 10;
    echo '<a href="page.php?start=' . $new_start . '">Next</a>';
    

    Edit: As the comments above suggest, you probably do not want to include() these files, as include() will attempt to interpret these files as PHP scripts. If you just need to get the contents of the text files, use file_get_contents instead.