Tutorial :PHP : Document root directory backslash problem



Question:

I'm trying to link to a stylesheet in my header file using $_SERVER["DOCUMENT_ROOT"] as follows:

<head>      <?php          print "<link href='".$_SERVER["DOCUMENT_ROOT"]."/include/style.css' rel='stylesheet' type='text/css' />";      ?>      <title>eLMS</title>    </head>  

Since i'm testing locally, i'm getting the path as:

<head>      <link href='C:\Users\wretrOvian\Documents\eLMS\site/include/style.css' rel='stylesheet' type='text/css' />      <title>eLMS</title>    </head>  

And this is not rendering in Firefox. It does in IE however. This is obviously a validation issue. BUT, i tried the same code on a server - with the same results. :(

How do i go about fixing this? The end product may or may not run on a Local server, so i need the code to be flexible..

I'm using Abyss Webserver x1 with PHP 5.2.8

I must use absolute paths - because i do not want to copy the include folder to every subdirectory of the app. I need to be able to refer to it from every location.


Solution:1

Just use this:

<head>      <link href='/include/style.css' rel='stylesheet' type='text/css' />      <title>eLMS</title>  </head>  

Or, if it is used locally:

<head>      <link href='../include/style.css' rel='stylesheet' type='text/css' />      <title>eLMS</title>  </head>  

The document root is for internal usage (inside of PHP) only, not for in your HTML.


Solution:2

Try using:

$_SERVER['HTTP_HOST']  


Solution:3

Don't use a filesystem absolute path, use a path relative to (but not including) the document root. In this case just /include/style.css.


Solution:4

For using local files from the browser, use the file scheme.

file://C:/dir/file.ext  file:///dir/file.ext  

Not sure if you need two or three slashes, probably two on windows with the drive letter, three on *nix with the root slash, though I seem to recall seeing three slashes with the drive letter. Try it! :P


Solution:5

Try using the DIRECTORY_SEPARATOR constant. It returns \ on Windows systems and / on *nix systems.


Solution:6

First of all, the document root is literally the directory that the web server's / is located at. You do not usually want to use this with any content on the web. Use / instead.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »