0

Right now I'm using

$file = $_SERVER["PHP_SELF"];

to get the current filepath.. but what I really want is to get each directory in a seperate value, rather than the entire path in one value.

To be precise... I have a filesystem that basically works like

website.com/x/y/file.php
website.com/x/z/file.php
website.com/x/file.php

And I was wondering if there was a method that allowed me to get all of those directories in seperate values.

For example, if I do

echo $dirone . "/n" . $dirtwo . "/n" . $file;

That it'll end up showing as

x
y
file.php

in the case of

website.com/x/y/file.php

or, alternatively, end up showing as

x

file.php

in the case of

website.com/x/file.php

I'm honestly not sure how to pull this off. I've found methods to at least extract ONLY the filename, but that leaves me without the rest of the directories.

3
  • Sidenote: Use "\n" instead of "/n" Commented Mar 6, 2014 at 0:26
  • That really matter? I've been taught to use forward slash.. Commented Mar 6, 2014 at 0:31
  • It's what PHP.net suggests and have been that since I started getting into PHP a couple of years ago and have been corrected once. But hey, if it works ;-) Commented Mar 6, 2014 at 0:33

1 Answer 1

2

You can use:

$files = explode(DIRECTORY_SEPARATOR, $path);
foreach ($files as $file) {
    printf("%s\n", $file);
}

The DIRECTORY_SEPARATOR constant is important when dealing with paths given by the operating system, since Windows will give you '\' and unixes '/'.

Sign up to request clarification or add additional context in comments.

2 Comments

@alex it does, but I have heard (rumor alert!) that it has a performance cost. I'm tempted to ask another SO question about that, after some research. (The context of this comment was about Windows automatically converting '/' to '\'.)
Tried this with $_SERVER["PHP_SELF"] replacing $path.. Works great! Thanks for the help xrash and @alex. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.