19.4. Splitting a Filename into Its Component Parts

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.

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

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

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.