Directory Paths
These are a few notes to myself about managing directory paths in PHP. Unlike other programming environments, PHP doesn't hide the ugliness of file paths too well. Consequently, the programmer must spend effort to organize the file hierarchy, and manage paths.
There are a few directory paths that are handy to know:
- The document root of your code.
- The path to the document root.
There are a few extra directories to add for an app framework:
- A place to write temporary files, below the doc root.
- A place to write temporary files, inaccessible to web surfers.
- A place for non-changing assets, like graphics.
- A place to upload files.
- A place for a config file.
- A place for a config file that contains passwords.
Also, it's best to create some rules about passing paths as arguments into functions. Here are my rules:
- All paths arguments shall end with "/" or the directory separator.
- At the start of functions, or in object setters, paths shall be trimmed of slashes, and have a slash appended: $path = rtrim('/',$path).'/';
- All path concatenations shall be written like: $path1 . $path2.
These rules just keep me from writing code like this: $path = $path1 . '/' . $path2, and losing track of whether there's a slash at the end of the path or not. Despite my better judgment, I use the literal '/' instead of the DIRECTORY_SEPARATOR constant. This'll change in my code over time. The hardest part is writing this:
$path = rtrim(DIRECTORY_SEPARATOR,$path).DIRECTORY_SEPARATOR;
