Skip to content

Instantly share code, notes, and snippets.

@lazysod
Created May 22, 2014 10:29
Show Gist options
  • Save lazysod/717a9f120346ca1c9df4 to your computer and use it in GitHub Desktop.
Save lazysod/717a9f120346ca1c9df4 to your computer and use it in GitHub Desktop.
Generate a canonical URL using PHP
<link rel="canonical" href="http://www.website.com<?php echo parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);?>">
@evandrocoan
Copy link

Wouldn't $_SERVER['REQUEST_URI'] allow XSS? Alternative:

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

-->

<link rel="canonical" href="http://domainname/index.php">
  1. https://www.webmasterworld.com/php/4404755.htm - Canonical link with PHP

@ludndev
Copy link

ludndev commented Sep 7, 2019

Hello. Take a look

<?php

// get the rigth protocol
$protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';

// simply render canonical base on the current http host ( multiple host ) + requests
echo $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

?>

Link : https://gist.github.com/ludndev/57e3e479f97b9269fb5b20801800e9ff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment