Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Enhancing a Simple PHP Application Cleaning URLs with Subfolders Using Absolute Server Paths

28,736 Points

Asbolute server Path and images

Hey there, I would like someone to explain me why we can't use Absolute server path to get an image displayed in our website, why It doesn't work as the path to that image seems to be good.

I know that can be used "only" to reference a PHP file for an include.

What I mean is that:


   <img src="<?php echo ROOT_PATH.$product["img"]; ?>" alt="<?php echo $product["name"]; ?>">

/* PATH in this case is this value :
 And It doesn't work, even if the path is still somehow good.


<img src="<?php echo BASE_URL.$product["img"]; ?>" alt="<?php echo $product["name"]; ?>">

/* PATH in this case is this value :
 And it works.

Moreover, as I'm running on a linux system, if I follow the path It gives me as reference when using absolute root path for the image, it works, I reach the image, It's normal after all.

So my question is why does it works for referencing files to include and not for images ? It 's not really logical to me...

The same applies for including files, why can't we use ROOT relative ? As the path still looks good once again.

Thank you

1 Answer

Robert Bojor
Robert Bojor
Courses Plus Student 29,439 Points

Using absolute paths for images is not a good practice for the web...

First, your web server should have permissions to access the full path ( /var and /var/www ) and it is not a good idea - Imagine tomorrow a vulnerability is found for that web server running on your system. That gives access to the attacker to your /var files and from there to other files located there.

Second, lets assume you don't run a server just for one website. Each website hosted on the same server would have access to the other website's files just because your web server has access rights outside the root of its domain.

I found that the best practice is to declare a base href="http://..../" in the header of the website and from there use relative paths like "img/img01.png", "css/style.css" and don't bother to keep the / in the front of the calls.

I use absolute paths to check if the file exists and the include statement uses relative paths.

if (file_exists($filesPath.'modules/'.$callModule.'/c.php'))   { include 'modules/'.$callModule.'/c.php'; }
// In this case $filesPath = "/var/www/website_folder/"