【发布时间】:2013-10-18 17:02:31
【问题描述】:
现在我使用以下代码将目录中的所有文件包含到我的站点中:
<?php foreach (glob("overzicht/projects/*.php") as $filename)
{
include $filename;
}
?>
但是当目录为空时,我希望他显示文本:“目录中没有找到文件。”
我该怎么做?
【问题讨论】:
标签: php file include directory
现在我使用以下代码将目录中的所有文件包含到我的站点中:
<?php foreach (glob("overzicht/projects/*.php") as $filename)
{
include $filename;
}
?>
但是当目录为空时,我希望他显示文本:“目录中没有找到文件。”
我该怎么做?
【问题讨论】:
标签: php file include directory
$listy = glob("overzicht/projects/*.php");
if (empty($listy)) {
echo "there are no files found in the directory";
} else {
foreach ($listy as $filename) {
include $filename;
}
}
【讨论】:
if (!$listy || empty($listy)),根据手册,glob Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error. 注意: On some systems it is impossible to distinguish between empty match and an error.
empty(false) 给你一个语法错误哈哈)。
<?php
$flag = true;
foreach (glob("overzicht/projects/*.php") as $filename)
{
include $filename;
$flag = false;
}
if ($flag)
{
print("There are no files found in the directory.");
}
?>
我确信有更好的方法来做到这一点......但这已经足够了。
【讨论】:
将它们作为数组抓取,测试数组长度,如果大于零,则包含它们,否则显示消息,如下例所示:
<?php
$files = glob("overzicht/projects/*.php");
if (count($files) == 0)
{
echo "There are no files found in the directory";
}
else
{
foreach($files as $file)
{
include $file;
}
}
?>
【讨论】:
glob 的结果是一个数组
$`files = glob("overzicht/projects/*.php"); foreach (`$`files as $filename) { 如果(文件存在(`$`文件名)){ 包含一次`$`文件名; } 别的 { echo '目录下没有文件。\n'; } } ?> 如果您的目录中有很多文件。试试这个......我希望它会出现
【讨论】:
添加标志以检测是否找到文件。
<?php
$found = false;
foreach (glob("overzicht/projects/*.php") as $filename)
{
if(file_exists($filename)) {
include $filename;
$found = true;
}
}
if(!$found) {
print("There are no files found in the directory.")
}
?>
【讨论】:
if(file_exists($filename)) { 的有趣用法。你能给我们举个例子,glob 找到了一些文件但它不存在吗?
$found = true 可能会错误地设置标志而没有进行文件检查。我的错...