H.J. Frost
H.J. Frost

Reputation: 303

What is the right way to set the correct path in PHP?

I am working on a PHP MVC framework and the problem I just found is with the path to specific files in directories. When I route to the function that renders the page, all the files defined in the template files including CSS and images weren't loaded.

Here's my folder structure

First of all, I set the path in the index.php which is the front controller with this code :

<?php
 // Path to system
 $system_path = str_replace('\\', '/', dirname(__FILE__)).'/system';
 $template_path = $system_path.'/templates';
?>

Just like any other php frameworks, I can use these path variables throughout the framework. So in my home template file (system/templates/home/home.php)I have the tag to call the style.css located in system/templates/home/css/style.css. So my link tag in the template file is

<link rel='stylesheet' type='text/css' href='<?= $template_path; ?>/home/css/style.css' />

When I render the page the absolute path to css file above is shown correctly as

C:/Appserv/www/mysite/system/templates/home/css/style.css

But the stylesheet is never loaded, and I don't know why. When I click the link to the css file it returns the 403 error with the weird path like this

You don't have permission to access      /mysite/C:/AppServ/www/mysite/system/templates/home/css/style.css 

This makes me confuse because the path is incorrect at this point as it starts with the name of the website followed by the path defined in the template file above.

Is there anyway to solve this problem?

Upvotes: 0

Views: 450

Answers (2)

Foad Tahmasebi
Foad Tahmasebi

Reputation: 1352

I think it's better if you define a "template_url" or "base_url" constant in your index.php or init.php:

define('TEMPLATES_URL','http://localhost/system/templates');

then use it in your html like this:

<link rel='stylesheet' type='text/css' href='<?php echo TEMPLATES_URL; ?>/home/css/style.css' />

Upvotes: 1

Shomz
Shomz

Reputation: 37701

When loading a CSS file into your webpage, you don't need the system file path, but the URL. So instead of:

<link rel='stylesheet' type='text/css' href='<?= $template_path; ?>/home/css/style.css' />

you need something like:

<link rel='stylesheet' type='text/css' href='/home/css/style.css' />

or, if you have the base URL defined:

<link rel='stylesheet' type='text/css' href='<?= $base_url; ?>/home/css/style.css' />

If you still want to access a local file, consider using the file:/// protocol instead (not recommended).

Upvotes: 3

Related Questions