简体   繁体   中英

PHP - displaying just PHP files from a directory and sub directories

This is my first project using PHP and I've been stuck on this for almost 2 days now! I want to get all my PHP files from a directory and any sub directories and display them in iframes. I've managed to get it to display all the files in the directory, but I only want the PHP files, please see below. Thanks in advance for any help/advice.

<?php
$path[] = 'work/*';

while(count($path) != 0)
{

$v = array_shift($path);
foreach(glob($v) as $item)
{
    if (is_dir($item))
        $path[] = $item . '/*';
    elseif (is_file($item))
    {
         printf(
  "<iframe width=420 height=150 frameborder=0 src='$item'></iframe>",
  ($file),$target);

    }
}
}
?>

work/*模式从work/*更改为work/*.php

Simple...replace $path[] = 'work/*'; with $path[] = 'work/*.php';

You're already using glob , this is the simplest way.

Change:

elseif (is_file($item))

To

elseif (is_file($item) && substr($item, -4) == '.php')

You can also use PHP's directory iterators, but the above is all you really need to do to get it working.

Eh, for fun, here's the iterator approach:

$dir = new RecursiveDirectoryIterator('work');
$iter = new RecursiveIteratorIterator($dir);
$regex = new RegexIterator($iter, '/^.+\.php$/');

foreach($regex as $filename)
{
  // do something with $filename
}

You should have better code :) I specially did not add iframe so you can edit it by yourself to get a bit more experience :)

<?php
$iterator = new RecursiveDirectoryIterator('work/');

$files_count = 0;

foreach( new RecursiveIteratorIterator($iterator) as $filename => $cur) {
    $file_info = pathinfo($filename);

    if($file_info['extension'] === 'php') {
        $files_count++;
        echo $filename . "<br />";
    }
}

echo "Total: $files_count files<br />";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM