2012-02-15 132 views
0

这里是我的代码 - 不知道为什么它不工作:PHP if语句比较变量没有返回true吗?

<?php 
$urlroot  = $_SERVER['HTTP_HOST']; 
$urllink  = "http://" . $urlroot; 
$DirPath  = getcwd() . "\n"; 
$InnermostDir = basename(rtrim($DirPath, '/')); 
if ($InnermostDir == $urlroot) { 
    $InnermostDir = 'home'; 
    echo $InnermostDir; 
}; 
?> 

如果我做$InnermostDir$urlrootecho,他们都表现出了域example.com。所以不知道为什么这不会返回true?

+2

你可以发布'var_dump($ InnermostDir,$ urlroot);''的输出吗? – rid 2012-02-15 20:22:39

+1

'string(16)“domain.com”string(15)“domain.com” - - 看起来好像我得到一个空白区域。如果你可以提供解决方案,我会检查你的答案 – Jared 2012-02-15 20:27:37

+0

你确定你做了正确的回声?重新添加回声并向我们显示输出。我相信''InnermostDir'会显示绝对目录路径(来自'/ var/www/yourdir'或其他东西),而urlroot来自URI ...如果它们不同,这并不令人感到意外。 – Nanne 2012-02-15 20:27:44

回答

4

$DirPath含有\n在端部,这是不被除去,因此该字符串将不相等。

rtrim($DirPath, '/')将只从最后删除/个字符,而不是\n。如果您想要删除\n,则需要使用rtrim($DirPath, "/\n"),或者在设置$DirPath时根本不要添加\n

0

环绕与微调两个变量(),所以:

<?php 
$urlroot  = $_SERVER['HTTP_HOST']; 
$urllink  = "http://" . $urlroot; 
$DirPath  = getcwd() . "\n"; 
$InnermostDir = basename(rtrim($DirPath, '/')); 
if (trim($InnermostDir) == trim($urlroot)) { 
    $InnermostDir = 'home'; 
    echo $InnermostDir; 
}; 
?> 
0

如果我把这个在我的/ var/WWW目录:

<?php 
$urlroot  = $_SERVER['HTTP_HOST']; 
$urllink  = "http://" . $urlroot; 
$DirPath  = getcwd() . "\n"; 
$InnermostDir = basename(rtrim($DirPath, '/')); 
var_dump($InnermostDir); 
var_dump($urlroot); 
if ($InnermostDir == $urlroot) { 
    $InnermostDir = 'home'; 
    echo $InnermostDir; 
}; 
?> 

并与本地主机/ test.php的调用它,我得到

串(4) “www” 的字符串(9 )“localhost”

哪一个会失败if