Php echo folder name using glob

The code below will contain 10 random files from any of the three folders listed in GLOB_BRACE.

, eg:

$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); 

      

I would like to repeat the folder name in the url given below $ thelist

$thelist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>';

      

So when it is displayed on my page, it reads.

<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>

      

Used code:

<?php 
$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); /* change php to the file you require either html php jpg png. */
shuffle($files);
$selection = array_slice($files, 0, 11);

foreach ($selection as $file) {
    $file = basename($file);
    if ($file == 'index.php') continue;

    $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
        $randomlist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>';
    }
?>
<?=$randomlist?>

      

+3


source to share


1 answer


glob()

will return the directory and filename. Therefore, unless you reassign $file

to basename($file)

, the entire line will remain unchanged for output. You can still check basename()

in if()

at continue

.



foreach ($selection as $file) { 
  // Call basename() in the if condition, but don't reassign the variable $file
  if (basename($file) == 'index.php') continue;

  $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
  // Using the full `$file` in the HTML output. No need for basename() or dirname().
  // Using htmlentities to encode the file path for an HTML attribute
  $randomlist .= '<p><a href="' . htmlentities($file, ENT_QUOTES) . '">'.$title.'</a></p>';
}

      

+1


source







All Articles