Created
November 24, 2011 15:30
-
-
Save gglnx/1391586 to your computer and use it in GitHub Desktop.
Add or remove trailing slash of the current URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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