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.

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

报告相同问题?

悬赏问题

  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥20 双系统开机引导中windows系统消失问题?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方
  • ¥15 关于生产日期批次退货退款,库存回退的问题