PHP 在列出的目录中查找特定文件
PHP find a specific file in directories listed
我正在制作一个文章系统,我需要include
目录中列出的目录中的所有文章。示例:
- 在目录 "articles"
中查找目录
- 在目录 "articles"
的目录中查找名为 "article.php" 的文件
- 包含名为 "article.php"
的文件
由于我是 PHP 的新手,我不知道该怎么做。感谢所有帮助!
这里有一个解决方案:
$base_dir = './articles';
$filename = 'article.php';
// Listing all directories in $base_dir
$directories = scandir($base_dir);
// Looping over the directories
foreach($directories as $directory) {
if (! in_array($directory, array('.', '..'))) {
$filepath = $base_dir.'/'.$directory.'/'.$filename;
// if the file exists, we include it
if (is_file($filepath)) {
include_once($filepath);
}
}
}
又快又脏...
$data = '';
$dir = "path_to_your_articles";
$dirHandle = opendir($dir);
$lookForThis = 'article.php';
while ($file = readdir($dirHandle)) {
if(!is_dir($file)){
if($file == $lookForThis){
$data .= $file;
}
}
}
closedir($dirHandle);
echo $data;
希望这对你有用...
我正在制作一个文章系统,我需要include
目录中列出的目录中的所有文章。示例:
- 在目录 "articles" 中查找目录
- 在目录 "articles" 的目录中查找名为 "article.php" 的文件
- 包含名为 "article.php" 的文件
由于我是 PHP 的新手,我不知道该怎么做。感谢所有帮助!
这里有一个解决方案:
$base_dir = './articles';
$filename = 'article.php';
// Listing all directories in $base_dir
$directories = scandir($base_dir);
// Looping over the directories
foreach($directories as $directory) {
if (! in_array($directory, array('.', '..'))) {
$filepath = $base_dir.'/'.$directory.'/'.$filename;
// if the file exists, we include it
if (is_file($filepath)) {
include_once($filepath);
}
}
}
又快又脏...
$data = '';
$dir = "path_to_your_articles";
$dirHandle = opendir($dir);
$lookForThis = 'article.php';
while ($file = readdir($dirHandle)) {
if(!is_dir($file)){
if($file == $lookForThis){
$data .= $file;
}
}
}
closedir($dirHandle);
echo $data;
希望这对你有用...