Incase you need to find a file's path and filename, use basename( ) to get the filename and dirname( ) to get the path.
$full_filename = '/usr/local/php/php.ini'; $base = basename($full_name); // $base is php.ini $dir = dirname($full_name); // $dir is /usr/local/php
You can aslo try pathinfo( ) to get the directory name, base name, and extension into an associative array.
For a practical example, to create a temporary file in the same directory where the existing file is, 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');
The elements in the associative array returned by pathinfo( ) are dirname, basename, and extension:
$info = pathinfo('/usr/local/php/php.ini');
print_r($info);
This will give the output:
Array
(
[dirname] => /usr/local/php
[basename] => php.ini
[extension] => ini
)
Using functions such as basename( ), dirname( ), and pathinfo( ) is better than splitting 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.
However, there is 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_filename = $dirname . '/' . $basename . '.' . $extension;
- Kiran's blog
- 728 reads













Post new comment