2011-06-03 71 views
1

声明我试图根据我的网站的根网址显示一个div标记,即如果该网址是dev.foo.com显示div如果其他www.foo.com不显示等。我想出了这如果基于url

<?php if (substr($_SERVER['REQUEST_URI'], 0, 5) !== 'dev.') { 
    echo '<div class="dev-site-stuff">THIS IS THE DEV SITE!!</div>'; 
} 
?> 

但它不工作,我不能看到一个理由 - 任何想法非常感谢!

+0

什么是'(!==)?它等于('==')或不等于('!=') – 2011-06-03 22:33:08

+3

@AR:'!=='是'==='的倒数。在PHP(和其他几种语言)中,三元等于比较类型和值。 – 2011-06-03 22:34:54

+3

AR,你错了。根据经验,我发现在告诉某人他们不知道他们在做什么之前最好进行检查。 – tomfumb 2011-06-03 22:35:23

回答

1
$url = explode('.', $_SERVER['HTTP_HOST'], 2); 

/* you might want pretty variable that exactly gets the subdomain. 
* $subdomain = $url[0] != "www" ? $url[0] : ""; 
* if($subdomain == "dev") { 
* // dev site... 
* }else if($subdomain == "") { 
* // www site... 
* } 
*/ 

if($url[0] == "dev") { 
    echo '<div class="dev-site-stuff">THIS IS THE DEV SITE!!</div>'; 
} 

substr,strpos等在这种情况下并不总是有效。这真好?

编辑:顺便读一下你的问题。

6

你应该使用$_SERVER['SERVER_NAME']

如果您有任何其他疑惑只是做一个print_r($_SERVER);实际看到的阵列是如何由

+4

有关每个密钥的更多详细信息,请查看文档(http://php.net/manual/en/reserved.variables.server.php) – 2011-06-03 22:33:13

+0

这里假设dev和live站点在不同的服务器上 – tomfumb 2011-06-03 23:20:08

+0

@user:从来没有听说过虚拟主机? – dynamic 2011-06-03 23:21:59

1

除了@职场英语对话回答你上面也比较长5的子串对一个长度为4的字符串,所以它永远不会是真的。

您CON使用strrpos这样

if (strrpos($_SERVER['SERVER_NAME'], 'dev.') > 0) { 

希望这有助于。