Contents that posted a long time ago may be obsolete and may not reflect my current opinion.
PHP has a very handy function to convert relative pathnames to absolute paths:
realpath(). However, it’s limited in at least two aspects which both make it inconvenient (and sometimes impossible) to use:
- It’s limited to current directory – you cannot specify an arbitrary path for «.». This is inconvenient because we don’t want to change CWD before each call to
realpath()and restore it afterwards.
- It works on already existing paths and files – this is because
realpath()also resolves symlinks to real paths. However, this is much more annoying – what if we’re try to get a path for a new file we’re going to create?
realpath()does a good job by resolving symlinks but it shouldn’t fail once it finds there’s no path below.
After struggling for some time with
realpath() I decided to write my own function to expand relative paths to absolute – and here it is :)
- It doesn’t depend on CWD, you can pass an arbitrary value for it.
- Two functions: Expand which works exactly like
realpath()but without its downsides; and ExpandLeaveLinks which does the same but doesn’t resolve symlinks.
- It works regardless if file/directory exists or not. If yes (and you’re not calling ExpandLeaveLinks but Expand), it will resolve symlinks until path exists. If no, it will skip the remaining path and leave it as is.