PHP - Finding the Directory Depth

Posted on 2009-05-26
Medium Priority
Last Modified: 2013-12-12
Hi there,

What I need is a simple way for PHP to return the current directory depth from the root of my website.

This may be something like counting the forward slashes, returning a number and running through case logic???

How can I achieve this??

Many thanx
Question by:wilson1000
  • 2
LVL 11

Expert Comment

by:Todd Mummert
ID: 24474752

If you know your paths are simple (i.e,   /a/b/c/d), the following may work for you.

count(split('/', $path));

or this to handle multiple /'s together

count(split('/+', $path));

still wouldn't handle a case like  /a/b/../c  correctly...since you'd have to canonicalize first.

Author Comment

ID: 24474835
Thank you. I really don't know what i'm doing here so could you help with the coding please.

I need to determine the current folder depth of the page being viewed.

So root would = 0
A directory off the root would = 1
A directory off of that directory would = 2, and so on...

Is this something you can help with?

Thank you

Accepted Solution

ChristianSchab earned 2000 total points
ID: 24474856
Try this:

$dir = $_ENV["DOCUMENT_ROOT"];
$parts = split("/", $dir);
$depth = count($parts);

Open in new window


Author Closing Comment

ID: 31585366
Thats great thanks!

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

624 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question