Skip to content

Instantly share code, notes, and snippets.

@gglnx
Created November 24, 2011 15:30
Show Gist options
  • Select an option

  • Save gglnx/1391586 to your computer and use it in GitHub Desktop.

Select an option

Save gglnx/1391586 to your computer and use it in GitHub Desktop.
Add or remove trailing slash of the current URL
<?php
/**
* Add or remove trailing slash of the current URL
*/
function correctTrailingSlash($base = "/", $trainlingSlash = false) {
// Load the URI data
$redirect = false;
$requestUri = $_SERVER["REQUEST_URI"];
$queryString = $_SERVER["QUERY_STRING"];
$serverName = $_SERVER["SERVER_NAME"];
$protocol = ( strtolower( substr( $_SERVER["SERVER_PROTOCOL"], 0, 5 ) ) == 'https' ) ? 'https': 'http';
// Parse the url
$url = parse_url($protocol . "://" . $serverName . $requestUri);
$requestUriPath = $url["path"];
// Correct base path
if ( "/" != substr( $base, "-1" ) )
$base = $base . '/';
// We are on the homepage!
if ( $base == $requestUriPath )
return;
// Correct the url if needed
if ( "/" != substr( $requestUriPath, "-1" ) && true == $trailingSlash ):
$redirect = true;
$canonicalUrl = "http://" . $serverName . $requestUriPath . "/";
elseif ( "/" == substr( $requestUriPath, "-1" ) && false == $trailingSlash ):
$redirect = true;
$canonicalUrl = "http://" . $serverName . substr($requestUriPath, 0, -1);
endif;
// Add the query string to the new url
if ( $queryString ) $canonicalUrl .= "?" . $queryString;
if ( $url["fragment"] ) $canonicalUrl .= "#" . $url["fragment"];
// Redirect if needed
if ( true == $redirect ):
header("Location: " . $canonicalUrl);
exit;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment