我遇到一个奇怪的问题,我可以在if-and-else语句中执行头文件函数,例如......
//www.example.com/search/title/harry+potter
$path = explode("/", trim(trim($_SERVER['REQUEST_URI']),"/"));
if(!$path){
//if array is empty go back to index
header("Location: /");
}
else if(!$path[1] || !$path[2]){
//if neither index 1 or 2 are set go back to index
header("Location: /");
}
如果没有满足if-and-else语句,则此代码不应重定向用户,但由于某种原因,它似乎将用户从第二个else-if语句重定向。
如果我将header()
函数替换为echo "test"
,则不会发生任何事情。
我很困惑,问题是什么?
答案 0 :(得分:0)
我可以建议你解决头痛吗?您可以使用URL Rewriting创建这个简短且易于搜索的网址,让您的生活更轻松。 Check this out
答案 1 :(得分:0)
您可能想检查一下您的假设。例如,如果$_SERVER['REQUEST_URI']
返回字符串/
,则explode函数将返回一个包含两个元素的数组,两个元素都包含空字符串。
如果您的URI在开头有//
字符串,则$path[0]
和$path[1]
都将为空字符串。
答案 2 :(得分:0)
我认为问题在于如何设置if条件。尝试这样的事情:
<?php
//www.example.com/search/title/harry+potter
$URI = "/search/title/harry+potter";
// Placeholder for $_SERVER['REQUEST_URI']
$path = explode("/", trim( trim( $URI ), "/") );
// Test $path as empty array
//$path = array();
// Test $path as empty string
//$path = "";
var_dump($path);
if( !isset($path) || empty($path) ){
//if array is empty go back to index
echo "Is empty $ path";
// header("Location: /");
} else if ( strlen($path[1]) < 1 && strlen($path[2]) < 1) {
//if neither index 1 or 2 are set go back to index
echo "$ path[1] and $ path[2] are both empty";
// header("Location: /");
} else {
echo "$ path is an array with value in position 1 and/or 2";
}