Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

$SERVER Question

Hey guys,

Just a quick question as I'm not 100% sure if the follow PHP method is OK to import a stylesheet as I'm just starting out with PHP and still not completely familiar with this sort of thing.

Here's the code I'm currently using:

<link href="<?php echo $SERVER['SERVER NAME']; ?>css/style.css" rel="stylesheet">

I want to be sure that this is an OK method and that is not some old world way of doing things, but I am sure open to any suggestions on how this could be done better, maybe Hampton Paulk could give his views.

Thanking you in advance,

Stu :)

2 Answers

Aaron Graham
Aaron Graham
18,033 Points

I use it in my code and it seems to work fine. This works especially well when you develop on a server under one url (for example development.example.com), and deploy to another url (example.com). One thing to watch out for is, if you are running under an Apache virtual host, this value comes from the "ServerName" attribute in your virtual host configuration. Make sure that is set correctly. Also, I should point out that it is 'SERVER_NAME' with an underscore.

EDIT: I also just noticed that you have $SERVER instead of $_SERVER

Would it be an idea to create an init file and store this as a constant? This would mean you could change paths of files quite easily from a single location ;)

Aaron Graham
Aaron Graham
18,033 Points

Tom Cawthorn - That's probably not a bad idea.The nice thing about using $_SERVER['SERVER_NAME'] is that if your server is set up correctly it makes moving your code between servers with different URLs a trivial matter. Changing one value in an init file wouldn't be that big a deal either though, and it would prevent any problems with incorrect server names. The down side would be that you couldn't deploy directly from your development environment unless your init file was smart enough to read some type of environmental variable. At that point though, you probably might as well just use the super global.

Thanks guys, that was a real help. :)