[thelist] PHP - get one directory from a path?

Simon evolt.org at isurus.com
Wed Dec 20 10:20:03 CST 2006


Hi Stephen,

> I'm trying to figure out a straightforward way to set a PHP variable
> to a particular directory in a path.
>
> For example:  I have http://www.example.com/main/something/inner/
> index.php
> The path can change, though.  Specifically, the directory "something"
> is arbitrary -- the script could be running in http://www.example.com/
> main/whatever/inner/ and so forth.
>
> When the script runs, I want to set a variable to = "something", or
> whatever that directory name happens to be.
>
> I know how to get the last directory name using dirname() and such,
> but I can't figure out how to get the directory two levels up....

How about this:
<?php
     $parts = explode( '/', $_SERVER['SCRIPT_NAME'] );
     $something = $parts[ (count( $parts ) - 3 ) ];

     echo "something == $something";
?>

You may want to put some error checking in there incase there aren't
enough directory levels in your path - this would cause $something to
be a null length string.

HTH,

   Simon





More information about the thelist mailing list