19.5.1 Problem
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.
19.5.2 Solution
$full_name = '/usr/local/php/php.ini'; $base = basename($full_name); // $base is php.ini $dir = dirname($full_name); // $dir is /usr/local/php
$info = pathinfo('/usr/local/php/php.ini');
19.5.3 Discussion
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( ):
$dir = dirname($existing_file); $temp = tempnam($dir,'temp'); $temp_fh = fopen($temp,'w');
$info = pathinfo('/usr/local/php/php.ini');
print_r($info);
Array
(
[dirname] => /usr/local/php
[basename] => php.ini
[extension] => ini
)
You can also pass basename( ) an optional suffix to
remove it from the filename. This sets $base to php:
$base = basename('/usr/local/php/php.ini','.ini');
Using functions such as basename( ), dirname(
), and pathinfo( ) is more portable than just separating a full
filename on / because they 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 /:
$dirname = '/usr/local/php'; $basename = 'php'; $extension = 'ini'; $full_name = $dirname . '/' . $basename . '.' . $extension;
You can pass a full filename produced like this to other PHP
file functions on Windows, because PHP accepts / as a directory
separator on Windows.