doujingke4981
doujingke4981
2011-11-28 23:48

PHP:如何获取当前URL的目录深度?

已采纳

I'm working on the 404 page for my company's site, and it has a $depth variable that says "../site/". This works fine for any bad urls in the base directory, but anything in a subfolder is grabbing the css files from the wrong place using the $depth variable. I tried $depth = '/site/' and it grabbed no css files at all. My question is, how can I have PHP figure out the $depth dynamically, specifically, the number of ../ to put in? If I can get a number or something, this is easy, but I can't seem to find a quick, easy way to do this.

Edit: Turns out, the 404.php file is only in one location, regardless of which directory the bad url is referencing. So, my real problem is probably not php-related at all. Why would a 404 page get a css file in one folder when reached from www.siteurl.com/404 but get a css file of the same name from a different folder when reached from www.siteurl.com/foo/bar?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • doulu6234 doulu6234 10年前

    Here's a function I wrote a few years ago, I use it on my website. It should help:

    <?
    function absolute_include($file)
             {
             /*
             $file is the file url relative to the root of your site.
             Yourdomain.com/folder/file.inc would be passed as
             "folder/file.inc"
             */
    
             $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
    
             if($folder_depth == false)
                $folder_depth = 1;
    
             include(str_repeat("../", $folder_depth - 1) . $file);
             }
    ?>
    
    点赞 评论 复制链接分享
  • dongqi1245 dongqi1245 10年前

    If you're just trying to pull in CSS, in your HTML head, you can just use /< path_to_css >.css

    By using a / at the beginning, you're telling the browser to go to the root directory of your site to look for the requested site.

    If you need the path via PHP, you can use

    $_SERVER['DOCUMENT_ROOT']
    

    which will give you the direct path to your site root directory which you can build from.

    点赞 评论 复制链接分享
  • duandai0373 duandai0373 10年前

    Use the absolute URL of the CSS files to avoid having to mess with paths like that.

    If this doesn't work for you for whatever reason try looking at the $_SERVER array, specifically $_SERVER['PHP_SELF'] and $_SERVER['DOCUMENT_ROOT'].

    点赞 评论 复制链接分享
  • dtl4521 dtl4521 10年前

    You have to map a known webpath to a known diskpath (like the web/diskroot). Based on that information you can derive where your current webpath points to.

    点赞 评论 复制链接分享

相关推荐