Dynamic Title and Meta Tags

Platform:  PHP
Published  Dec 10, 2007
Updated  Dec 10, 2007
This is a very simple PHP snippet that will set $title, $meta_keywords and $meta_description for use in your page header. You'll need to create meta_tags.txt which will use this format:

page_name.html|page title|meta tags|meta description
page_name2.html|page title2|meta tags for page 2|meta description for page 2

To use the code either save it at the top of your header file or save it as get_meta.php and add this line of code to your header:

Code
 

You can reference the $title, $meta_keywords and $meta_description variables in your header like this:

Code
 
<?php

$database = 'meta_tags.txt';
$meta_db = fopen($database, 'r');

$page = $_SERVER['SCRIPT_NAME'];
$page = substr($page, 1);

while($data = fgetcsv($meta_db, 9000, '|'))
{
if($data[0] == $page)
{
$title = $data[1];
$meta_keywords = $data[2];
$meta_description = $data[3];
}
}

?>

Comments

Sign in to comment.
jrharper   -  Jan 07, 2013
hawkee,

I have the title part working on my site,I used [if($category) print $category; if($subcategory) print $subcategory; print $title;] so that it would diplay $title before anyone clicked on $category or $subcategory. The value of $title is Products, so it just prints after $category or $subcategory is clicked, so my title becomes Art($category)Products($title).

My problem is that each page is loaded inside of my header as page1.html. All listings on the page are from $category or $subcategory. I'm not sure how to go about getting the keywords part to work. I don't need keywords for every page, just $category or $subcategory.

Your welcome to look at my site to see what I'm talking about.

Thank You
Hawkee  -  Jan 07, 2013
I'm not too clear what you mean. Can you illustrate your point with some example URLs and the code changes you made?
jrharper  -  Jan 07, 2013
My variables:

$page = $_GET['page'];
$search = $_GET['search'];
$search = str_replace("-", " ", $search);
$search = stripslashes($search);
$category = $_GET['category'];
$subcategory = $_GET['subcategory'];

variable I added:

$title = ' Products';

The change I made:

<title><?php if($category) print $category; if($subcategory) print $subcategory; print $title; ?></title>

this is the area I want to change because they stay the same:

<meta name="description" content="The Largest Product Directory on the Internet for Downloadable Software, Services, and Products. "/>

<meta name="keywords" content="Art,Entertainment,Betting Systems,Betting,Business,Investing,Computers,Internet,Cooking,Food,Wine,E-Business,E-Marketing,Education,Employment,Jobs,Fiction,Books,Games,Green Products,Health,Fitness,Home and Garden,Languages,Mobile,Parenting and Families,Politics,Current Events,Reference,Self-Help,Software,Services,Spirituality,New Age,Alternative Beliefs,Sports,Travel"/>

jrharper  -  Jan 07, 2013
jrharper  -  Jan 07, 2013
The menu system on the left side is a list of the values in $category and $subcategory. what I want to do is link seperate description and keyword to each value in $category and $subcategory.
jrharper  -  Jan 07, 2013
What I am wondering is if I can create a php page structured like this

if($category='Arts_and_Entertainment') then ($meta_keywords='') and ($meta_description='');
if($category='Betting_Systems') then ($meta_keywords='') and ($meta_description='');
if($category='Business/Investing') then ($meta_keywords='') and ($meta_description='');

with all of my $categories and $subcategories keywords and descriptions and then call this page from my header?
Hawkee  -  Jan 07, 2013
Sure, you can do that, but the format would be more along these lines:
Code
 
jrharper  -  Jan 07, 2013
I tried both ways and neither one works. I can change the title, but not the meta tags. It leaves the meta tag blank even if I do just $meta_description alone.
jrharper  -  Jan 08, 2013
My title works using this:
<title><?php if($category) print $category; if($subcategory) print $subcategory; print $title; ?></title>
$title = ' Products';

onload title = Products, if any catagory (say Art) is clicked title = Art Products, and the same with the subcatagories

Is there a way that I could use the out-put from that to load keywords and descriptions for each category/subcategory?

Hawkee  -  Jan 09, 2013
@jrharper I'm sorry, but I'm just not very clear about what you are doing. Are you using the code provided on this page or are you building something entirely different? If you need some general programming questions answered you might want to try searching StackOverflow. It's a very good Q&A development resources.
jrharper  -  Jan 11, 2013
Problem Solved !!!
First I want to thank you for the code and letting me use this place as a backboard for my thoughts.

I wanted to use your code, but I only have page1.html that is displayed inside a header. What is displayed on page1.html is controlled by 2 variables that make up the menu, $category and $subcategory. To solve my problem I created a title.php file that is an if/elseif statement.

if($category == '' && $subcategory == '') {
print('Products');
}
elseif ($category == 'Arts-and-Entertainment') {
print('Arts and Entertainment');
}
elseif($category == 'Betting-Systems') {
print('Betting Systems');
}
elseif($category == 'Business-/-Investing') {
print('Business / Investing');

It has $subcategory in the same file lower down.(it's 746 lines long) I did this to format the output. then I put include('title.php') between the title tags.

Now I can copy the file twice and save them as description.php and keyword.php and all I have to do is change the print('') statements and then include them between the tags.
Sign in to comment

Hawkee   -  Dec 11, 2012
@pleb If this is the case then aren't you using JavaScript to bring up each page?
 Respond  
pleb   -  Dec 11, 2012
the point is that my site uses a single page name and #xyz to show different content (but really they are different pages), a lot of sites do this now in order to avoid reloading and displaying content faster. but the problem indeed is that this page has a unique meta data right now. these are really different pages, but they are all under a single php file. for example gmail does this too: https://mail.google.com/mail/u/0/?shva=1#inbox
 Respond  
Hawkee   -  Dec 11, 2012
@pleb You'll probably need to reload the page with the anchor appended as a query string, but I'm not sure what your ultimate goal is. Anchors usually represent a particular point on a page and not a full page in itself. They're for browsers and not for spiders, so meta tags that are dependent on anchors don't make sense.
 Respond  
pleb   -  Dec 11, 2012
Hello @Hawkee,

I found this code to get the anchor using javascript and cookies.

<script language="javascript">
query=location.href.split("#")
document.cookie='anchor='+query[1];

if (query[1] != "<?php echo $_COOKIE['anchor'];?>") {
window.location.reload()
}
</script>

<script language="php">
$passedaname=$_COOKIE['anchor']
</script>

But so now, how do I capture what is returned in the anchor and add it the my page name (index.php in get_meta.php so that it gets the full URL (index.php#home? should I define it inside $page = ?

thanks a lot!!!
 Respond  
Stew   -  Nov 29, 2012
Wow thanks @Hawkee really nice snippet!!!
 Respond  
Hawkee   -  Nov 20, 2012
@pleb You'll need to incorporate JavaScript to read the hash portion of the URL. That information is not sent to PHP. Here is some more information, http://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url
 Respond  
pleb   -  Nov 20, 2012
Hi Hawkee,
Running in a problem as my page is unique but shows different content using the # tag: index.php#home , index.php#contact etc...
I got it working on index.php but can't figure out how to structure get_meta and the data file to make it look at #home instead of just index.php

Thanks for your help
 Respond  
PhilC   -  Aug 13, 2012
Thanks for the code example. Simple and just what I needed!
 Respond  
nikadorji   -  Mar 24, 2012
hello Hawkee
Please can u explain me how the following code works..


<?php

$database = 'get_meta.php';
$meta_db = fopen($database, 'r');

$page = $_SERVER['SCRIPT_NAME'];
$page = substr($page, 1);
echo $page;

while($data = fgetcsv($meta_db, 9000, '|'))
{
if($data[0] == $page)
{
$title = $data[1];
$meta_keywords = $data[2];
$meta_description = $data[3];
}
}

?>
 Respond  
blondsplash   -  Oct 06, 2011
Hawkee, disregard the last comment, I GO IT WORKING!!!!

Thanks so much for the code, you are awesome!!!!
 Respond  
blondsplash   -  Oct 05, 2011
Hawkee, Can you help?

I created a file and named it get_meta.php this is the code on that file:

<?php

$database = 'get_meta.php';
$meta_db = fopen($database, 'r');

$page = $_SERVER['SCRIPT_NAME'];
$page = substr($page, 1);
echo $page;

while($data = fgetcsv($meta_db, 9000, '|'))
{
if($data[0] == $page)
{
$title = $data[1];
$meta_keywords = $data[2];
$meta_description = $data[3];
}
}

?>

?movie=211|Horror Movie: 100 Feet|100 Feet, ghost story horror movie, ghost scary movie|A ghost story


I'm calling the file with this code on the header <?php include('get_meta.php'); ?> and have added this code also:
<title><?php print $title; ?></title>
<meta name="keywords" content="<?php print $meta_keywords; ?>"/>
<meta name="description" content="<?php print $meta_description; ?>" />

I have a MySQL movie database in my server. In the database the movie id is 211, the url for the same movie is http://www.besthorrormovielist.com/movieinfo.php?movie=211.

Do you see any typos and in get_meta.php is my format correct? I have been trying to fix this on my site for months and cannot get it to work.
 Respond  
UnknownInc   -  Sep 13, 2011
Hey Guys, any thoughts on grabbing the URL (for instance, my users have their own urls (mysite.com)/(username)
I want to be able to rip username from URI and insert into Title so the page has unique content (currently all profiles have the same title/desc/kw) I was thinking i could regex the url, but would need some help incorporating it properly.
any ideas!

Thanks
 Respond  
mabe   -  Jul 12, 2011
I have been using this script for a few years now, but it suddenly stopped working after my host migrated to a new server. I don't see any error, but the titles also don't appear anymore.. we just see the page URL instead of the title. Any idea what I can do to correct this?

Thanks!
 Respond  
zahidrouf   -  Jun 01, 2011
Thanks for sharing this useful post ......
 Respond  
polyfade   -  May 20, 2011
I run MAMP, so my site sits in a subdirectory folder. Example: http://mysite.com/myfolder/test.php

test.php, meta_tags.txt, get_meta.php are on the same level.

In the meta_tags.txt file, I could have prepended 'myfolder' in front of all my page files to make this work. Example: myfolder/test.php

However that's counterproductive. Hawkee mentioned "strip the directory from $page"
However, I'm not fluent in PHP, so I didn't know how to do handle precisely. I searched the web for awhile to find a "solution."

Since the fix wasn't illustrated in this post, here is the solution that worked for me:

Comment out, but don't delete since you may need it later:
$page = substr($page, 1);

Add this snippet just below:
$page = ltrim(strrchr($_SERVER['PHP_SELF'], '/'), '/');

Basically, that seems to remove the subdirectory name from the path in order to make adding dynamic meta tags possible.
 Respond  
soppnox   -  Dec 22, 2010
In wordpress blog how i can implement dynamic php code... if I'm posting new article it will need to add Dynamically post Title will come meta Title, post describtion will come meta description, Tags will come meta keywords Is that any idea...?
 Respond  
alleyndn   -  Dec 07, 2010
I am new to this. I need to add a different title, metaname keywords and metaname description tags to every page of my site. My site is a drupal site and I having some difficulty doing it. I am not sire what I am missing?
 Respond  
rolmike   -  Dec 07, 2010
Hi

Great script I have the same problem as someone else above to get the script to work in sub folders. I have put the get_meta.php and meta_tags.txt in the root folder (public_html). Then I have sub folder with files and I used the echo $page varible and it says that the files are in "en/file1.php and "en/file2.php" and so on. Then I have put the patch "en/file1.php" in the meta_tags.txt but it want generate the tags.

Any suggestions?
 Respond  
denise   -  Nov 18, 2010
Hi,

I am finding problem with meta tag implementation,in the following code,can anybody suggest how can i implement meta tags in following code:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><?php StoreOwnerPageTitle(); ?></title>
<link rel="stylesheet" href="./css/index.css" type="text/css">
<link rel="stylesheet" href="./css/Sassy_Ecomm2.css" type="text/css">
<script type="text/javascript" src="./jscripts/jscookmenu.js"></script>
<script type="text/javascript" src="./jscripts/swfobject.js"></script>
<script type="text/javascript" src="./jscripts/wwb7.js"></script>
<LINK HREF="storefront-files/style/stylesheet.css" TYPE="text/css" REL="stylesheet">
<script src="storefront-files/javascript/main.js" type="text/javascript"></SCRIPT>
</head>

As whenever i have tried its not get implemented correctly,

Thanks
 Respond  
Hawkee   -  Sep 07, 2010
Ritz, it's probably the same problem. Just echo your variables to see what the exact problem is.
 Respond  
Ritz   -  Sep 07, 2010
correct it's for directory. when i include directory in meta_txt it works perfect. but I don't know how to stript the directory in get_meta.php.

what about meta information disapeearing http://www.ritzinfotek.in/ not the index.php
 Respond  
Hawkee   -  Sep 06, 2010
Ritz, so there's the problem. Your $page variable contains the directory so it doesn't match $data[0]. You can either include the directory in your meta txt file or you can strip the directory from $page. Basically you just need to make sure $page and $data[0] match.
 Respond  
Ritz   -  Sep 06, 2010
also I've seen meta informations is appearing properly when there is file name only. See it here:

http://www.ritzinfotek.in/

In this case the meta information has been totally disappeared..

any suggestion..
 Respond  
Ritz   -  Sep 06, 2010
while usiring print_r($data).. getting this

Array ( [0] => index.php [1] => meta title [2] => meta tags [3] => meta description1 )
Array ( [0] => aboutus.php [1] => metal title [2] => meta tags [3] => meta description2 )

and so on.

while echo $page the out is:
directory/index.php
 Respond  
Hawkee   -  Sep 06, 2010
I'd just start echoing all the variables to see exactly what is happening. For example inside the while loop you can do a print_r($data) to see the contents of the $data hash. Then you might also want to echo the $page variable to make sure it's being set properly.
 Respond  
Ritz   -  Sep 05, 2010
yes. it's in the same directory in local server. getting errros like:


<title><br /> <b>Notice</b>: Undefined variable: title in <b>C:\wamp\www\directory\index.php</b> on line <b>11</b><br /></title>

<meta name="Keywords" content="<br />
<b>Notice</b>: Undefined variable: meta_keywords in <b>C:\wamp\www\directory\index.php</b> on line <b>12</b><br />
"/>

<meta name="description" content="<br />
<b>Notice</b>: Undefined variable: meta_description in <b>C:\wamp\www\directory\index.php</b> on line <b>13</b><br />
"/>
 Respond  
Hawkee   -  Sep 04, 2010
Is meta_tags.txt in the same directory as index.php? If not you need to adjust the $database variable to point to the proper location.
 Respond  
Ritz   -  Sep 04, 2010
oh. everything works when it hosted in server. It won't work on my wamp local server..

see it here.. http://www.ritzinfotek.in
 Respond  
Ritz   -  Sep 04, 2010
so I repeated the variable once more time but now the meta is taking but from the las line of database.. :

while($data = fgetcsv($meta_db, 9000, '|'))
{
if($data[0] == $page)
{
$data[1]=$title;
$data[2]=$meta_keywords;
$data[3]=$meta_description;
}
$title = $data[1];
$meta_keywords = $data[2];
$meta_description = $data[3];
}
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.