Search code examples
php

How do I get the base URL with PHP?


I am using XAMPP on Windows Vista. In my development, I have http://127.0.0.1/test_website/.

How do I get http://127.0.0.1/test_website/ with PHP?

I tried something like these, but none of them worked.

echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.

Solution

  • Try this:

    <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>
    

    Learn more about the $_SERVER predefined variable.

    If you plan on using https, you can use this:

    function url(){
      return sprintf(
        "%s://%s%s",
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME'],
        $_SERVER['REQUEST_URI']
      );
    }
    
    echo url();
    #=> http://127.0.0.1/foo
    

    Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME.

    <VirtualHost *>
        ServerName example.com
        UseCanonicalName on
    </VirtualHost>
    

    NOTE: If you're depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.