Search code examples
phpnavigation

Previous/next page links using PHP


I have 80 PHP pages - I want to have next/back buttons on each page, automatically linking to previous/next pages. The pages are numbered sequentially ( page1.php, page2.php, page3, etc).

I would like an easier approach than having to manually link every button on each student profile page to go to the next/previous student pages.

Anyone have any ideas how to do this?


Solution

  • This is a relatively robust solution (considering the requirements):

    $pinfo = pathinfo($_SERVER["SCRIPT_FILENAME"]);
    $reqpath = dirname($_SERVER["REQUEST_URI"]);
    
    if(preg_match("/(.*?)(\d+)\.php/",  $pinfo["basename"], $matches)) {
        $fnbase = $matches[1];
        $fndir = $pinfo["dirname"];
        $current = intval($matches[2]);
        $next = $current + 1;
        $prior = $current - 1;
        $next_file = $fndir . DIRECTORY_SEPARATOR . $fnbase . $next . ".php";
        $prior_file = $fndir . DIRECTORY_SEPARATOR . $fnbase . $prior . ".php";
    
        if(!file_exists($next_file)) $next_file = false;
        if(!file_exists($prior_file)) $prior_file = false;
    
    
        if($prior_file) {
            $link = "$reqpath/" . basename($prior_file);
    
            echo "<a href=\"$link\">Prior</a>";
        }
    
        if($prior_file && $next_file) {
            echo " / ";
        }
    
        if($next_file) {
            $link = "$reqpath/" . basename($next_file);
    
            echo "<a href=\"$link\">Next</a>";
        }
    }
    
    • It checks if the file next/prior actually exists
    • It supports multiple enumerations like {bla1, bla2, bla3} and {foo1, foo2, foo3}