动态页面标题通过PHP

时间:2015-05-12 19:13:56

标签: php

我试图通过PHP动态设置页面标题。我的页面标题位于head.php文件中,该文件包含在每个页面中,因此不能单独执行此操作。

我写了下面的代码,我无法理解为什么它不起作用:

<?php
$currentUrl = $_SERVER['SERVER_NAME'];
$currentpage = $_SERVER["SCRIPT_NAME"];
if("hoosiermommapcs.com"==$currentUrl) {
 $currentTitle = "Home";
}
else if("/index.php"==$currentpage) {
 $currentTitle = "Home";
}
else if("/dispatch.php"==$currentpage) {
 $currentTitle = "Request Pilot Cars";
}
else if("/invoice.php"==$currentpage) {
 $currentTitle = "Submit Invoice";
}
else if("/gallery.php"==$currentpage) {
 $currentTitle = "Image Gallery";
}
else if("/contact.php"==$currentpage) {
 $currentTitle = "Contact Us";
}
$siteTitle = "Hoosier Momma Pilot Car Services | ";
?>

我的页面标题代码是:

<title><?php echo($siteTitle . $currentTitle); ?></title>

该代码适用于设置&#34; Home&#34;但不是任何其他人。如果我去invoice.php,它仍然会说&#34; Home&#34;在标题中。

感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

两个问题:

  1. $currentUrl.$currentpage将包含完整的主机名和查询字符串,但您只需检查if else中的查询字符串
  2. 如果网址包含参数,您的解决方案可能不会有效,例如/index.php?rel=xxx。尝试使用$_SERVER["SCRIPT_NAME"]代替$_SERVER['REQUEST_URI']

答案 1 :(得分:1)

我删除了一行并让它正常工作。如果其他人遇到这个问题,则将其作为答案发布:

我删除了:

if("hoosiermommapcs.com"==$currentUrl) {
 $currentTitle = "Home";
}

并制作了我的代码:

<?php
$currentpage = $_SERVER["SCRIPT_NAME"];
if("/index.php"==$currentpage) {
 $currentTitle = "Home";
}
else if("/dispatch.php"==$currentpage) {
 $currentTitle = "Request Pilot Cars";
}
else if("/invoice.php"==$currentpage) {
 $currentTitle = "Submit Invoice";
}
else if("/gallery.php"==$currentpage) {
 $currentTitle = "Image Gallery";
}
else if("/contact.php"==$currentpage) {
 $currentTitle = "Contact Us";
}
$siteTitle = "Hoosier Momma Pilot Car Services | ";
?>

名称:

<title><?php echo($siteTitle . $currentTitle); ?></title>

答案 2 :(得分:0)

要单独获取文件,您可以使用:

$_SERVER['ORIG_PATH_INFO'];

这与URL参数无关。它也独立于包含,并获取您在地址栏中看到的信息。以下是一些结果:

URL                                     RESULT
http://example.com/index.php            /index.php
http://example.com/about.php?a=dsa      /about.php
http://example.com/t/t.php?t=t          /t/t.php

如您所见,这也与URL参数无关。从那里,您可以执行以下操作:

switch( $_SERVER['ORIG_PATH_INFO'] )
{
    default:
        $title = "";
        break;
    case "/index.php":
        $title = "Home";
        break;
    case "/about.php":
        $title = "About";
        break;
}

如果开关/案例令人生畏,你可以使用字典:

$file = $_SERVER['ORIG_PATH_INFO'];
$titleDict = [
    "/index.php" => "Home",
    "/about.php" => "About"
];

if( array_key_exists($file,$titleDict) )
    $title = $titleDict[$file];
else
    $title = "";
相关问题