2011-04-27 25 views
1

我看到了下面的線程,但它是一個有點超出我的變量...添加到網頁標題標籤基於從URL

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變量 - 例如如果URL open = true2添加「car gallery」,如果URL open = true3,則添加「cat gallery」,如果URL沒有變量,則不向標題添加任何內容。

任何人都可以協助嗎?我一直在尋找,但無論是錯過了職位或它沒有被覆蓋(我的業餘水平)。

非常感謝。保羅。

回答

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>

+0

我已經很快測試過這個,因爲它包含了將URL變量轉換爲更適合標題的功能。在Firefox中工作。非常感謝。 – Paul 2011-04-27 10:34:14

+0

謝謝大家的意見/幫助。我會密切關注這個話題 - 特別是關於任何持續的潛在攻擊問題。 – Paul 2011-04-27 10:40:49

+0

很高興我們可以幫助保羅。 @Treffynnon感謝您添加htmlentities()。接得好。 – Ben 2011-04-27 10:46:07

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

PHP可以取從URL查詢字符串(www.yoursite.com?page=1 &貓=狗等)的信息。您需要獲取該信息,確保它不是惡意的,然後才能將其插入到標題中。這裏有一個簡單的例子 - 爲您的應用程序,請確保您清理數據,並檢查它沒有惡意:

<?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和您應該找到有助於解決問題的信息。

+0

這是開放的攻擊。請參閱:http://en.wikipedia.org/wiki/Cross-site_scripting – Treffynnon 2011-04-27 10:17:38

+0

這是一個簡單的例子。 – 2011-04-27 10:21:13

+0

是的,但它仍然是重要的告誡它。 – Treffynnon 2011-04-27 10:28:05

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中。