Skip to content

Instantly share code, notes, and snippets.

@mattsah
Created October 3, 2011 21:24
Show Gist options
  • Save mattsah/1260300 to your computer and use it in GitHub Desktop.
Save mattsah/1260300 to your computer and use it in GitHub Desktop.
Canonical URLs
<?php
function get_url($with_query_string = TRUE, $canonical_filter = array())
{
$query = NULL;
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$port = ':' . $_SERVER['SERVER_PORT'];
$host = $_SERVER['SERVER_NAME'];
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
? 'https'
: 'http';
if (($scheme == 'http' && $port == 80) || ($scheme == 'https' && $port == 443)) {
$port = NULL;
}
if ($with_query_string) {
$canonical_params = $_GET;
foreach ($canonical_filter as $filter) {
$match = FALSE;
if (strpos($filter, '*') !== FALSE) {
$regex_match = str_replace('*', '(.*?)', $filter);
foreach ($canonical_params as $param => $value) {
if (preg_match('/' . $regex_match . '/', $param)) {
unset($canonical_params[$param]);
}
}
} else {
foreach ($canonical_params as $param => $value) {
if ($filter == $param) {
unset($canonical_params[$param]);
}
}
}
}
$query = '?' . http_build_query($canonical_params);
}
$url = $scheme . '://' . $host . $port . $path . $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment