Split Filename into its Component Parts in PHP

0
Your rating: None

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;

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

SEO Architect,SEO Specialist reflect my values.

By enduring black hat methods the SEO industry is setting itself up for washout and sleepwalking into oblivion.

Jobs in India