Library contents

PHP is_file and is_dir

Distinguish regular files from directories.

A simple example

is_file and is_dir

  1. Start with A regular file a.txt
  2. Do this Test whether it is a directory
  3. Result No
A regular file and a directory have different entry types.

Syntax

PHP syntax
is_file($upload)
Run these examples in PHP

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

php lesson.php

Tell an uploaded file apart from its folder

A registration desk receives documents through an upload folder. The clerk needs to confirm that the submitted entry is a regular file and that the enclosing location is a directory before processing the batch.

Resultfile and folder
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 {
    $upload = $base . '/upload';
    if (!touch($upload)) throw new RuntimeException('Cannot create upload');
    if (is_file($upload) && is_dir($base)) echo "file and folder", PHP_EOL;
} finally {
    foreach (['upload'] as $name) {
        $path = $base . '/' . $name;
        if (is_link($path) || is_file($path)) unlink($path);
        elseif (is_dir($path)) rmdir($path);
    }
    rmdir($base);
}
Output
file and folder

The upload and its enclosing workspace have different entry types.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenspring / alto.txt
Worked resultRegular file

Locate a workshop handout

An instructor stores the current template in a class folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenceramics / glaze.pdf
Worked resultRegular file

What to watch for

Status checks describe the instant of inspection. Handle failure at the subsequent open.

Documentation for is_file and is_dir