Search code examples
phpphp-include

PHP Include based on URL parameters


I have a directory that contains 30 php includes with various blocks of html. I am trying to include 5-6 of these files based on the parameters of the url. The files are named like this:

1.php 2.php 3.php ... 30.php

And the URL looks like this:

www.example.com?include=1-4-14-20-29

I need something like this but I know this isn't valid:

$include = @$_GET['include'];   // hyphen separated list of file names.

$arr = explode("-", $include);  //explode into an array
foreach ($arr as $filename) {
include $filename."php";

}

Result I am trying to get:

<php
include '1.php';
include '4.php';
include '14.php';
include '20.php';
include '29.php';
?>

Thanks for any help you can offer.


Solution

  • I would loop through the array, so would take the minimum and the maximum values, like this:

    <?php
    $include = $_GET['include'];   // hyphen separated list of file names.
    
    $arr = explode("-", $include);  //explode into an array
    
    # What's the min and max of the array?
    $max = max($arr);
    $min = min($arr);
    
    # Just to see what's happening.
    echo $max."-".$min;
    
    # Start at the lowest value, and work towards the highest in the array.
    for ($i = $min; $i <= $max; $i++) {
    
    # Include the nth php file
    include $i.".php";
    }
    
    ?>
    

    EDIT

    Oh sorry, just seen I've misunderstood your question, you are not looking for ranges, but individual calls. Then this one's for you:

    <?php
    $include = $_GET['include'];   // hyphen separated list of file names.
    
    $arr = explode("-", $include);  //explode into an array
    foreach ($arr as $filename) {
    include $filename.".php";
    }
    
    ?>