PHP getting document path relative to site root
You have to use $_SERVER["DOCUMENT_URI"]
instead of $_SERVER["DOCUMENT_ROOT"]
, like this:
echo "<link rel='stylesheet' type='text/css' href='" . dirname($_SERVER['DOCUMENT_URI']) . "/styles/basicblue.css'/>";
I ended substracting the web root path to get the relative one
str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER["SCRIPT_FILENAME"]);
So instead of /home/u/username/example.com/public_html/webfolder/index.php
you will get /webfolder/index.php
edit: in constructed case your filename somehow can repeat document root, so the code above will not work correctly. This is more bulletproof (count symbols and remove them)
substr($_SERVER["SCRIPT_FILENAME"],strlen($_SERVER['DOCUMENT_ROOT']));
Echoing what Mike said above, in my experience, $_SERVER['DOCUMENT_ROOT']
is only the best option for finding files on the server. If you need php to inlcude or require something, find the server side path with DOCUMENT_ROOT
.
However, css files are client side. They're included from the relative website path. If you were to instead just do
<link rel='stylesheet' type='text/css' href='/styles/newscontent.css'/>
The opening /
in the href tells the browser to always retrieve it from root of your domain: http://yourdomain.com/styles/newscontent.css
.