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

7
  • php.net/manual/en/function.rtrim.php (rtrim( $url, '/' ). Commented Feb 19, 2016 at 20:36
  • I've already tried this and still no luck with it :/ Commented Feb 19, 2016 at 20:37
  • 2
    Can you show how you tried that, and what the url looked like after the rtrim? Commented Feb 19, 2016 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... Commented Feb 19, 2016 at 20:48
  • 1
    'https' and 'http' will never have a trailing slash. you're applying rtrim() in the wrong place Commented Feb 19, 2016 at 20:48

1 Answer 1

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, '/' );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.