Lacrifilm Lacrifilm - 1 month ago 15
PHP Question

Subfolder don't load the style.css

I have a

.htaccess
file that redirects all the URL request to my
index.php


AcceptPathInfo On
RewriteEngine on
RewriteBase /Projects/tester/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?request=$1 [L,QSA]


Inside my index.php I have a code that include the URL file:

<?php

if(isset($_GET['request'])){
include('pages/'.$_GET['request'].'.php');
}else{
echo 'index';
}

?>


If my URL is
localhost/Projects/tester/green
my index will include a file called
green.php
that exists inside the folder
pages
.

inside pages/green.php I have this code:

<link rel="stylesheet" type="text/css" href="style.css">
<div id="greenBox">
This box is green!
</div>


When I run that URL I can see a large green div with an text inside.

Great, now lets create a folder called
subs
inside the folder
pages
and create a file called
yellow.php


<link rel="stylesheet" type="text/css" href="style.css">
<div id="yellowBox">
This box is yellow!
</div>


When I run this URL
localhost/Projects/tester/sub/yellow
I can see the text but the
style.css
don't load (I can't see the yellow div).

If all the content is being included in the
index.php
and
style.css
file is in the same folder as the
index.php
, why
green.php
can load the
style.css
but the
yellow.php
not?

I can see the yellow div only if I add
../style.css
inside the yellow.php, but if it is to work on this way, I believe we should use
../style.css
on green.php while in yellow.php use
../../style.css
, no?

Is there a way to solve this? is problem in .htaccess?

Answer

Of course the external browser doesn't understand where your files are located on the server, so if you are in the following situation (from the browser's perspective):

http://localhost/Projects/tester/green
 -> hey browser, load "style.css"
 -> browser loads http://localhost/Projects/tester/style.css

But if you change the "virtual" path:

http://localhost/Projects/tester/sub/yellow
 -> hey browser, load "style.css"
 -> browser loads http://localhost/Projects/tester/sub/style.css

So you have three solutions here, in order of my personal preference:

1) Use absolute URLs for loading css data, optionally using a PHP var:

<link rel="stylesheet" type="text/css" href="/Projects/tester/style.css">
<link rel="stylesheet" type="text/css" href="<?php echo $base_path; ?>/style.css">

2) Use the <base> html element in head: (warning: it applies to ALL relative urls in the page: links, images, etc.)

<head>
  <base href="http://localhost/Projects/tester/" />
</head>

3) If using absolute URLs is not an option, you can calculate how many "virtual subdirectories" you are down and generate a prefix like this:

<?php
// first calculate $virtal_subdirs_number
$relative_urls = str_repeat("../", $virtual_subdirs_number);
?>
<link rel="stylesheet" type="text/css" href="<?php echo $relative_urls; ?>/style.css">