CSS doesn't do its thing when using $_SERVER['DOCUMENT_ROOT']
I'm learning about PHP classes and objects right now so to get some experience with it, I'm converting my site using these instead of static html to save me typing the same generic html over and over again.
So, this is part of the object:
<link rel=\"stylesheet\" type=\"text/css\" href=\"".$_SERVER['DOCUMENT_ROOT']."/main.css\" />
...which produces this in the browser (after I changed the root directory in the Apache config file):
<link rel="stylesheet" type="text/css" href="C:/wamp/www/test/main.css" />
My problem is that the styling in that css file isn't showing on the page. If I copy the location of the css file shown in the browser (when click开发者_StackOverflowing 'view source') and enter it into the url bar, the css file appears. So if I can access it this way, why can't the webpage access it? I'm assuming it has something to do with permissions but if I right-click on the css file in my file browser, it says that everything can at least read it...
Any help would be greatly appreciated.
Save yourself some effort. This works just as well:
<link rel="stylesheet" type="text/css" href="/main.css" media="all" />
This assumes, of course, that the CSS file is in the document root.
What if someone else visits your page, and hasn't got a file named "C:/wamp/www/test/main.css"
? ;-) I guess the implementation differs per browser, but a site shouldn't be able to access resources on the visitor's computer this way.
You want to use either the website name (obtainable through $_SERVER['SERVER_NAME'
), or an absolute URL (/test/main.css
) and set the $_SERVER['SERVER_NAME']
in a <base href>
element.
You reach web sites though URLs (http://example.com/foo/bar
), not through their path in the server's hard disc (C:\www\example\htdocs\foo\bar\index.html
). This applies to everything: documents, pictures... and style sheets.
You don't really need to take the web root from a PHP variable unless you are planning to change it. Most of the times, you can hard-code /
happily. I suggest the compromise of creating your own constant:
define('WEB_ROOT', '/');
?>
精彩评论