【问题标题】:PHP if URL equals this then perform actionPHP 如果 URL 等于 this 然后执行操作
【发布时间】:2012-03-01 20:01:31
【问题描述】:

所以我有一个页面标题,它是 Magento 模板的一部分;我希望它显示 2 个选项中的 1 个,具体取决于 URL 是什么。如果 URL 是选项 1,则显示标题 1。如果 URL 是其他内容,则显示标题 2。这是我想出的,但它使我的页面崩溃:

<div class="page-title">
<h1><?php
$host = parse_url($domain, PHP_URL_HOST);
if($host == 'http://domain.com/customer/account/create/?student=1') {
echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!')
}
else
{
echo $this->__('Create an Account')
}
?></h1>
</div>

有人有什么想法吗?

编辑:所以它应该是这样的?

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'http://domain.com/customer/account/create/?student=1')

【问题讨论】:

  • “让我的页面崩溃”是什么意思?您是否查看错误消息?进一步:您在哪里定义变量 $domain?
  • 这部分页面加载之前的所有内容,然后停止。没有错误信息
  • 我从这个帖子获得了 $domain:stackoverflow.com/questions/1122261/…

标签: php if-statement


【解决方案1】:

您是否在寻找页面当前所在的 URL?你用错了parse_url;也就是说,如果您只想获取主机或域,即仅“dev.obtura.com”。看起来你想要的不止这些。此外,您永远不会设置$domain 变量,因此parse_url() 不知道如何处理它。就目前而言,您的if 语句将始终返回“创建帐户”。

改为将$host 设置为$_SERVER 变量:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

您还需要从检查中删除“http://” - $host 将只包含“http://”之后的所有内容

正如Aron Cederholm 建议的那样,您需要在 echo 语句的末尾添加分号 (;)。

所以,您的 PHP 代码应该如下所示:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'domain.com/customer/account/create/?student=1') 
{
    echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!');
}
else
{
    echo $this->__('Create an Account');
}

【讨论】:

  • @miles 编辑了我的答案以包含您的观察,以供其他人查看答案。
【解决方案2】:

我不确定您获取的域是否正确。我不太了解 parse_url,而且您还没有向我们展示 $domain 的定义。

通常,如果我想获得域名,我会这样做:$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] 然后是您的其余代码。

if, else 语句对我来说似乎是合法的,所以我会尝试上面的方法,看看情况如何。 ;)

编辑:哎呀,约翰打败了我。 :)

【讨论】:

  • 见我上面的编辑。我试过了,结果和以前一样。
【解决方案3】:

您应该在 if-else 中的语句中添加分号。

if($host == 'http://dev.obtura.com/customer/account/create/?student=1') {
    echo $this->__('Create an account if you are a Post Graduate Endodontic Resident and receive our resident pricing. Please fill in all required fields. Thank you!');
}
else
{
    echo $this->__('Create an Account');
}

【讨论】:

  • 页面不再崩溃,但语句不起作用。我仍然收到第二个“创建帐户”标题
  • 尝试回显 $host 以亲自查看为什么它不等于您想要的 url。
  • @miles 您是否尝试按照我的建议设置 $host?
  • 像这样: if ($host == '...') { echo 'Success: ', $host, PHP_EOL;回声 $this->__('...'); } else { echo '失败:', $host, PHP_EOL; echo $this->__('创建一个帐户'); }
  • 另外,尝试按照@john 和 Jack BeePee 描述的方式设置 $host。
猜你喜欢
  • 2010-11-10
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多