PHP get public facing base directory from URL

I would like to be able to tell what the base directory of a site is automatically. Say I have a website in this location on a Unix machine:

/home/webserver/mywebsite

And it’s publicly accessible here:

http://mywebsite.devserver.com/temp

I would like to be able to move the website from “temp” to the root of the site without having to manually change my php configuration files in my framework.

I guess what I need is the public facing directory of the index.php file, so say I have a .htaccess rewrite rule that means:

http://mywebsite.devserver.com/pages/page

.. will load the index.php file in the root and will return the page at /pages/page, I would need the “base directory” of the site to return “” (An empty string) because the site belongs directly after the domain name. But then say I put the site inside a directory like:

http://mywebsite.devserver.com/directory/pages/page

I would need the “base directory” to return “directory” so I can use it within the code elsewhere.

I am very sorry if this sounds vague and I will happily explain more if needed but any help will be greatly appreciated!


Source: .htaccess

1 Comment

  1. Digin Dominic

    You can use this code in your DOCUMENT_ROOT/.htaccess file:

    RewriteEngine On

    RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)1$
    RewriteRule ^.*$ - [E=BASE:%2]

    It compares REQUEST_URI variable (which is the complete URL) with the URI matched by RewriteRule (which is relative to current path) and gets differential in %{ENV:BASE} variable.

    Reply

Leave a Reply