如何读取目录和过滤文件,然后回显它们?

时间:2013-06-23 21:22:46

标签: php

大家好我试图读取一个名为people的目录,其中填充了php,html,png,jpeg和其他格式。我正在尝试过滤我想要phphtml文件的文件,然后将其回显。

这是我的尝试,由于它没有echo任何文件,因此无效:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Khviii ICT</title>
</head>

<body>
<div align="center" ><h1>Welcome to KHVIII ICT</h1></div>
<?php
$dir="/people";
$allowed_view= array("php","html");
$files=scandir($dir);
foreach ($files as $file)
{
        $filexplosion=strtolower(end(explode('.',$file)));
    if (in_array($allowed_view,$filexplosion)) 
        {
    echo $file;
    } 
}
?>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

目录路径不正确且in_array参数不按顺序排列。修正后的PHP代码如下:

    $dir = __DIR__ . "/people";
    $allowed_view = array("php", "html");
    $files = scandir($dir);
    foreach ($files as $file) {
        $filexplosion = strtolower(end(explode('.', $file)));
        if (in_array($filexplosion, $allowed_view)) {
            echo $file;
        }
    }

答案 1 :(得分:0)

试试这个:

$files=scandir($dir);
echo "I have found " . count($files) . " files<br>"; // Are you sure there are files found?
foreach ($files as $file)
{
$filexplosion = substr($file, strrpos($file, "."));
echo $filexplosion; // just to check if you're getting the right value
if (in_array($allowed_view,$filexplosion)){
  echo $file;
} 

答案 2 :(得分:0)

经过几次研究后,我使用了gelb()。 这是代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>khvii index</title>
</head>

<body>
<?php
foreach (glob("people/"."*.php",GLOB_BRACE) as $filename) {
    $phpexplode = end(explode("/",$filename));
    echo'<a href="'.$filename.'"><input type="button" value="'.$phpexplode.'"></a><br />';
}
foreach (glob("people/"."*.html",GLOB_BRACE) as $filename) {
    $htmlexplode = end(explode("/",$filename));
    echo'<a href="'.$filename.'"><input type="button" value="'.$htmlexplode.'"></a><br />';
}
?>
</body>
</html>