1

This code outputs paths

function genPost() {
// Gives the full path leading to this file starting at root.
// eg. /var/www/html
$path = dirname(__FILE__);

// Lists the folders and files of the chosen path.
// FYI the variable is now an array!!!
$pathContents = scandir($path);

function makePath($key) {
    $path = dirname(__FILE__);
    $folders = scandir($path);
    $two = $folders[$key];
    $three = $path . "/" . $two;
    echo $three . "<br>";
    //echo include("$three");
}
$key = 0;
// array_key_exists() returns false when the key to the array doesn't exist
while (array_key_exists($key, $pathContents)) {
    makePath($key);
    $key = $key + 1;
}
}
echo genPost();

However when I change the while to this, it outputs nothing to the browser.

while (array_key_exists($key, $pathContents)) {
    include "makePath($key)";
    $key = $key + 1;
}

My question is how do I avoid putting a directory in the include, and instead use a variable to tell the php interpreter where to pull the file from for the include function.

Christian
  • 11
  • 2

1 Answers1

1

The issue that you are using include with string ( normally should be string that represent a path, not a function call) and this will cause wrong path error.

your makePath should be:

function makePath($key) {
    $path = dirname(__FILE__);
    $folders = scandir($path);
    $two = $folders[$key];
    $three = $path . "/" . $two;
    return $three;
}

and when you need to use it:

while (array_key_exists($key, $pathContents)) {
   include makePath($key);
   $key = $key + 1;
}
gharabat
  • 177
  • 2
  • 13
  • Oh my! This is it!! I didn't catch the typo in echo $three . "
    "; Thank you for the advice on the return, as well!!!
    – Christian Apr 02 '20 at 06:36