douduoyan5943 2013-12-06 15:46
浏览 42
已采纳

DOCUMENT_ROOT或SERVER_NAME用于在子文件夹中显示CSS

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?

  • 写回答

1条回答 默认 最新

  • duanjing2013 2013-12-06 17:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?