Search code examples
phpincludehref

DOCUMENT_ROOT or SERVER_NAME for showing CSS in subfolders


I am facing this weird problem in my localhost. I have a directory in htcdocs named sdis. I have included all the files using DOCUMENT_ROOT in the files placed under the root folder. All the css, links, images, etc. show up fine. Now, when I add a subfolder under sdis and try to include the same, I get a raw page without any css. This is the code for both root folder files, as well as subroot folder files.

<?php include $_SERVER["DOCUMENT_ROOT"].'/sdis/includes/overall/header.php'; ?>        
Whatever Data
<?php include $_SERVER["DOCUMENT_ROOT"].'/sdis/includes/overall/footer.php'; ?>

And after a lot of playing around, I realized, the link href part is something like:

href="bootstrap/css/bootstrap.css"

Now that, is not an absolute link of course. Hence the including DOCUMENT_ROOT is working only for the root folder files. So I tried using both of these:

<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['SERVER_NAME'] ?>/bootstrap/css/bootstrap.min.css">

and

<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['DOCUMENT_ROOT'] ?>/bootstrap/css/bootstrap.min.css">

And it still doesn't show up any css or images for the files in subroot folder.

Could anyone help me out including the css links, images, etc, so that all the css and images shows in the root folders, subfolders, etc. too properly?


Solution

  • HTML is not aware of the PHP script which generated it.

    The best way to solve it is to set virtual server ( /etc/hosts on Linux, %windir%/system32/drivers/hosts on Windows, may need restart)

    127.0.0.1       localhost
    127.0.0.1       vm1.localhost
    

    and then in httpd.conf

    <VirtualHost *:80>
        ServerName localhost
        DocumentRoot "/htcdocs"
    </VirtualHost>
    
    <VirtualHost *:80>
        ServerName vm1.localhost
        DocumentRoot "/htcdocs/yourfolder"
    </VirtualHost>
    

    After this modification (and restart of your server you can access your pages by http://vm1.localhost/, the DOCUMENT_ROOT is set to yourfolder

    Note: after setting the DOCUMENT_ROOT, I recommend to use

    href="/bootstrap/css/bootstrap.min.css"
    

    instead of

    href="<?php echo $_SERVER['DOCUMENT_ROOT'] ?>/bootstrap/css/bootstrap.min.css"
    

    creating HTML paths using PHP system variables may force you to rewrite the code when you move to hosting with different settings, whereas pure HTML remains independent.