You want to find a file's path and filename; for example, you want to create a file in the same directory as an existing file.
Use basename( ) to get the filename and dirname( ) to get the path, as shown in Example 24-12.
Getting path components
Use pathinfo( ) to get the directory name, base name, and extension in an associative array, as in Example 24-13.
Getting path components and file extensions
To create a temporary file in the same directory as an existing file, use dirname( ) to find the directory, and pass that directory to tempnam( ). This is what Example 24-14 does.
Creating a temporary file in a particular place
The dirname( ) function is particularly useful in combination with the special constant __FILE__, which contains the full pathname of the current file. This is not the same as the currently executing PHP script. If /usr/local/alice.php includes /usr/local/bob.php, then __FILE__ in bob.php is /usr/local/bob.php. This makes __FILE__ useful when you want to include or require scripts in the same directory as a particular file, but you don't know what that directory is and it isn't necessarily in the include path. Example 24-15 demonstrates.
Including files relative to the current file
If the code in Example 24-15 is in the /usr/local directory, then it includes /usr/local/functions.php and /usr/local/classes.php. This technique is particularly useful when you're distributing code for others to use. With it, you don't have to require any configuration or include path modification for your code to work properly.
Using functions such as basename( ), dirname( ), and pathinfo( ) is more portable than just splitting up full filenames on the / character because the functions use an operating-system-appropriate separator. On Windows, these functions treat both / and \ as file and directory separators. On other platforms, only / is used.
There's no built-in PHP function to combine the parts produced by basename( ), dirname( ), and pathinfo( ) back into a full filename. To do this you have to combine the parts with . and the built-in DIRECTORY_SEPARATOR constant, which is / on Unix and \ on Windows.
24.4.4. See Also
Documentation on basename( ) at http://www.php.net/basename, dirname( ) at http://www.php.net/dirname, pathinfo( ) at http://www.php.net/pathinfo, and __FILE__ at http://www.php.net/language.constants.predefined.