【发布时间】:2021-04-23 14:10:28
【问题描述】:
当 URL 上没有指向文件时,谁能帮助显示错误页面而不是显示我的文件目录?例如,在附图中,我只需删除 thefile.php 并在浏览器上输入 URL,例如 www.mywebsite.com/foldername/ 而不是 www.mywebsite.com/foldername/thefile.php,它会显示该文件夹下的所有文件。我希望它将用户重定向到错误页面,而不是显示此文件夹中的所有文件。
【问题讨论】:
当 URL 上没有指向文件时,谁能帮助显示错误页面而不是显示我的文件目录?例如,在附图中,我只需删除 thefile.php 并在浏览器上输入 URL,例如 www.mywebsite.com/foldername/ 而不是 www.mywebsite.com/foldername/thefile.php,它会显示该文件夹下的所有文件。我希望它将用户重定向到错误页面,而不是显示此文件夹中的所有文件。
【问题讨论】:
一种方法是在该文件夹内创建一个 index.php 文件,内容如下:
<?php
$dir = "."; // the directory you want to check
$exclude = array(".", "..", "index.php"); // ignore . .. and file itself
$files = scandir($dir);
$files = array_diff($files, $exclude); // delete the entries in exclude array from your files array
if(!empty($files)) {
echo "there are files";
}
else
{
header("Location: /404.php");
}
?>
当你访问http://url/folder时,index.php是默认加载的php文件,所以如果文件夹中除了index.php文件没有其他内容,就会显示404页面(你有用处理 404 错误的任何页面替换 /404.php 页面)
我假设您也可以使用 .htaccess 中的一些正则表达式来完成此操作
【讨论】: