Library contents

PHP basename and dirname

Extract the last component of a path and the name of its parent.

A simple example

basename and dirname

  1. Start with Path notes/a.txt
  2. Do this Read its final component
  3. Result a.txt
The directory portion is notes and the last name is a.txt.

Syntax

PHP syntax
basename(dirname($path))
Run these examples in PHP

Save one example at a time as lesson.php. Use PHP 8.2 or later.

php lesson.php

Print a receipt name and its folder

A school store receives a path from the checkout system. The receipt printer needs just the filename, while the filing clerk needs the name of the folder that holds it.

First output line014.txt
lesson.php
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
    $path = $base . '/receipts/014.txt';
    echo basename($path), PHP_EOL, basename(dirname($path)), PHP_EOL;
} finally {
    rmdir($base);
}
Output
014.txt
receipts

The final component is the receipt name. Its parent supplies the filing category.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.

Givenspring / alto.txt
Worked resultalto.txt

Locate a workshop handout

An instructor stores the current template in a class folder. Build the nested path and read its final name for the screen.

Givenceramics / glaze.pdf
Worked resultglaze.pdf

What to watch for

These are pathname operations. A trailing separator or filesystem root may need separate handling.

Documentation for basename and dirname