Book HomePHP CookbookSearch this book

19.5. Splitting a Filename into Its Component Parts

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

Use basename( ) to get the filename and dirname( ) to get the path:

$full_name = '/usr/local/php/php.ini';
$base = basename($full_name);  // $base is php.ini
$dir  = dirname($full_name);   // $dir is /usr/local/php

Use pathinfo( ) to get the directory name, base name, and extension in an associative array:

$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');

The elements in the associative array returned by pathinfo( ) are dirname, basename, and extension:

$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.

19.5.4. See Also

Documentation on basename( ) at http://www.php.net/basename, dirname( ) at http://www.php.net/dirname, and pathinfo( ) at http://www.php.net/pathinfo.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.