padawanTony padawanTony - 11 months ago 63
PHP Question

MVC - CSS links

I am relatively new to this whole MVC structure for web apps.

Here is the structure of my project.

enter image description here

The file you see on the right of the picture is inside the 'Views' folder.

When I want to link a css file, why does the path have to be


Why is it not


What you are looking at, is the HTML that is sent to the users' browser. The browser does not know anything about the structure of your application. It simply reads that href link, and downloads the file from<link>, where <link> is /css/main.css for example.

When configured correctly, the web root of your website is in your /public folder. That means, anything that a browser requests, is relative to your web root. Thus, if you want to link to a css file, you need to think of that link relatively to your projects web root, not relatively to your project root.

An example: Say, you create a new project in /home/user/AwesomePhpProject. Now, /home/user/AwesomePhpProject is called your project root.

In your project root, you create a directory, public. You configure that directory to be your web root, using VirtualHost (when using Apache) or the root directive (when using Nginx). /home/user/AwesomePhpProject/public is now your web root. When a browser requests /css/main.css, it will be directed to /css/main.css relative to your web root. In our case, that will be /home/user/AwesomePhpProject/public/css/main.css.

Most modern applications separate the project and web root, for security reasons.