Welcome to WebmasterWorld Guest from 23.22.140.143

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Canonical link with PHP

     
2:50 pm on Jan 7, 2012 (gmt 0)

Full Member

5+ Year Member

joined:Apr 26, 2009
posts: 246
votes: 2


Hi Guys,

I am trying to use the following on the template to automatically generate canonical links on every page when page is requested.

<link rel="canonical" href="<?php $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];echo $url;?>">


this works just fine, but only if your page is static .html doc with no query string in it such as ".html?blablabla"

Question:

Is there any way to clean the output so that it only outputs the actual link to be only .html and without any query string attached, even if there is one in the request URL?
4:12 pm on Jan 7, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3123
votes: 0


Try SCRIPT_NAME instead of REQUEST_URI.
4:45 pm on Jan 7, 2012 (gmt 0)

Full Member

5+ Year Member

joined:Apr 26, 2009
posts: 246
votes: 2


Worked like it should have.

Thanks!

Is there any security risks with using following on static .html pages?

<link rel="canonical" <?php
function fetch_url() {
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
return $url;}
echo "href=\"" . fetch_url() . "\">";?>
5:42 pm on Jan 7, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3123
votes: 0


Presumably you are parsing .html pages with PHP?

I think this is OK regarding security.

Just a thought.... however, you could tidy it up and define the function at the start of your script. It could be more useful if fetch_url() returned just the URL? Or have a function that returns the whole canonical tag? But if you are not using the function anywhere else then you don't need a function for this.
8:18 pm on Jan 7, 2012 (gmt 0)

Full Member

5+ Year Member

joined:Apr 26, 2009
posts: 246
votes: 2


I thought so too and decided against it. I think that instead I will just use it like below:

<link rel="canonical" href="<?php $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];echo $url;?>">