根据URL中的变量添加到页面标题标记

时间:2011-04-27 09:45:16

标签: php url variables tags title

我见过以下帖子,但它有点超出我的想法......

How can I change the <title> tag dynamically in php based on the URL values

基本上,我有一个页面index.php(没有php只是命名为未来的证据 - 也许现在!)。它包含许多灯箱样式的画廊,可以通过URL中的变量从外部链接触发 - 例如index.php?open = true2,index.php?open = true3等。

我想index.php标题标签 - 包含现有静态数据+根据网址变量添加其他单词 - 例如如果URL打开= true2添加“car gallery”,如果URL open = true3添加“cat gallery”,如果URL没有变量,则不对标题添加任何内容。

有人可以帮忙吗?我一直在寻找,但要么错过了帖子的点,要么没有被覆盖(我的业余水平)。

非常感谢。保罗。

5 个答案:

答案 0 :(得分:1)

在php脚本的顶部放置:

<?php

# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');

# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');

?>

然后使用它来包含您的自定义标题:

<title>Pauls Great Site<?php echo htmlentities($title); ?></title>

答案 1 :(得分:0)

<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>

答案 2 :(得分:0)

<?php
    if( array_key_exists('open', $_GET) ){
        $title = $_GET['open'];
    }else{
        $title = '';
    }
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>

<body>
The content of the document......
</body>

</html>

http://www.w3schools.com/TAGS/tag_title.asp

http://php.net/manual/en/reserved.variables.get.php

答案 3 :(得分:0)

PHP可以从URL查询字符串中获取信息(www.yoursite.com?page=1&cat=dog等)。您需要获取该信息,确保它不是恶意的,然后您可以将其插入标题中。这是一个简单的示例 - 对于您的应用程序,请确保您清理数据并检查它是否是恶意的:

<?php
$open = "";

// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>

<html><head><title>This is the title: <?php $open ?></title></head>

PHP有很多用于转义可能包含令人讨厌的东西的数据的函数 - 如果你查找htmlspecialchars和htmlentities,你应该找到有用的信息。

答案 4 :(得分:0)

其他一些答案可供滥用,请尝试以下方法:

<?php
    if(array_key_exists('open', $_GET)){
        $title = $_GET['open'];
    } else {
        $title = '';
    }
    $title = strip_tags($title);
?>
<html>
    <head>
        <title><?php echo htmlentities($title); ?></title>
    </head>
    <body>
            <p>The content of the document......</p>
    </body>
</html>

否则正如@Ben所提到的那样。首先在PHP中定义标题,以防止人们直接将文本注入HTML。