我在if, elseif和else上遇到了一些麻烦。
如果url是example.com,则包含sites/home.php
Elseif url为example.com/test include sites/$url.php
其他包括sites/404.php
if ($url=='')
include_once "sites/home.php";
elseif (What to put here!!!? I need the elseif to happend if it is possible to include the $url file){
include_once "sites/$url.php";
}
else {
include_once 'sites/404.php';
}
希望你们理解我的问题。我无法用其他方式来解释
if ($url=='') {
include_once "sites/home.php";
} elseif (file_exists($url)) {
include_once "sites/$url.php";
} else {
include_once 'sites/404.php';
}
我是这样做的。
if ($url=='') {
include_once "sites/home.php";
}else if (file_exists("$url.php") && is_readable("$url.php")){
include_once "sites/$url.php";
}else {
include_once 'sites/404.php';
}
读取文档(但未测试):
"include returns FALSE on failure and raises a warning"
裁判:http://www.php.net/manual/en/function.include.php
那么,你的代码应该是:
if ($url=='') {
include_once "sites/home.php"
}
else {
if (include_once sites/$url.php) {
// Do nothing : it worked !
}
else {
include_once "sites/404.php";
}
}
您似乎想使用include
指令来查找文件是否存在。按照手册:
处理返回:include在失败时返回FALSE并引发警告。
因此,您需要:
- 使用
@
操作符 抑制警告 -
false
与===
算子的比较
它会工作,但它会是一个可怕的黑客。我建议你重新考虑一下你的逻辑,这样你就可以事先知道哪些文件可以被包括在内。
您可以测试该文件是否存在并且脚本具有读取它的权限。
if ($url=='') {
include_once "sites/home.php";
}
elseif (file_exists( $url . ".php") && is_readable($url . ".php")){
include_once "sites/" . $url . ".php";
}
else {
include_once 'sites/404.php';
}