2012-02-15 137 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