TheOptimizationIdiot - 6:03 pm on Mar 25, 2013 (gmt 0)
Looks like a bunch of extra processing to check for and strip a query string to me. (The above looks like it will also miss /location.ext? -- no variables or info -- since in that case the query string is empty, but the ? does make the URI a different location.)
header("Location: http://www.example.com" . str_replace('?'.$_SERVER['QUERY_STRING'],$_SERVER['REQUEST_URI']), true, 301);
I'd definitely recommend against this. A long time ago when the canonical was first introduced I ran into issues on pages with www and without both being declared as the canonical since it was flexible (determined by the page location) and there was an issue in the .htaccess that skipped the canonicalization in some instances.
Much better to hard-code a canonical (www.example.com at least) or "build it" out of the information like you would the page if the site is dynamic and not rely on everything working 100% the way it should to not have every page with the information presented declared as the canonical version of the page, because when everything works the way it should the canonical is unnecessary since there's only one version of the page and a canonical should point from the non-canonical location to the canonical location like a 301 redirect would.
Basically, if you code the canonical to be flexible based on the location a visitor is viewing and you have any duplication you have multiple canonical locations. If you don't have any duplication you don't need the canonical since there's only one version of the page, so obviously it's the canonical.