0

So I've created this function that get's the URL of the Website, but I also want it to remove the trailing / as well.

So far I have this:

function base_url() {
    $base_url = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';

    return $base_url.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

But I don't know how to remove the trailing / from the URL.

I've also tried to add the rtrim but still no luck:

function base_url() {
    $base_url = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    $base_url = rtrim($base_url, '/');

    return $base_url.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

Image of the URL -

enter image description here

Stephen
  • 515
  • 1
  • 14
  • 31
  • http://php.net/manual/en/function.rtrim.php (`rtrim( $url, '/' )`. – Kenney Feb 19 '16 at 20:36
  • I've already tried this and still no luck with it :/ – Stephen Feb 19 '16 at 20:37
  • 2
    Can you show how you tried that, and what the url looked like after the `rtrim`? – Kenney Feb 19 '16 at 20:38
  • Why add an image? Just paste the URL into the question and surround it with backticks (`\``). Blanking out a section of it just makes it harder to find the issue... – SeinopSys Feb 19 '16 at 20:48
  • 1
    'https' and 'http' will never have a trailing slash. you're applying rtrim() in the wrong place – Brad Kent Feb 19 '16 at 20:48
  • take it - http://stackoverflow.com/questions/12494515/remove-unnecessary-slashes-from-path – Dmytro Feb 19 '16 at 20:49
  • @DJDavid98 I've added the URL, also @Brad Kent well something is adding the trailing `/` as you can see from the URL there is an extra one their – Stephen Feb 19 '16 at 20:53

1 Answers1

3

Try it like this:

function base_url() {
    $base_url = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    $base_url.= '://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    return rtrim( $base_url, '/' );
}
Kenney
  • 9,003
  • 15
  • 21