Oihana PHP

assertFile.php

Table of Contents

Functions

assertFile()  : void
Asserts that a file exists and meets specified accessibility and MIME type requirements.

Functions

assertFile()

Asserts that a file exists and meets specified accessibility and MIME type requirements.

assertFile(string|null $file[, array<string|int, mixed>|null $expectedMimeTypes = null ][, bool $isReadable = true ][, bool $isWritable = false ]) : void

This function performs a series of checks on a given file:

  1. Ensures the file path is not null or empty.
  2. Confirms that the path points to a valid file.
  3. Optionally checks if the file is readable.
  4. Optionally checks if the file is writable.
  5. Optionally validates the file's MIME type against a provided list.
Parameters
$file : string|null

The path of the file to check. Cannot be null or empty.

$expectedMimeTypes : array<string|int, mixed>|null = null

Optional array of allowed MIME types. If provided, the file's MIME type must match one of these.

$isReadable : bool = true

Whether to assert that the file is readable. Default: true.

$isWritable : bool = false

Whether to assert that the file is writable. Default: false.

Tags
throws
FileException

If the file path is null, empty, or if the file does not exist or is not accessible.

example

Basic usage: check if a file exists and is readable.

$file = 'test.txt';
file_put_contents($file, 'data');
try
{
   assertFile($file);
    // Continue ...
}
catch (FileException $e)
{
    // Handle error...
}
unlink($file);

Check for specific MIME types.

$file = 'document.txt';
file_put_contents($file, 'some text');
try
{
     // Will pass because a .txt file is typically 'text/plain'.
     assertFile( $file , ['text/plain', 'application/pdf'] );
}
catch ( FileException $e )
{
    // Throws an exception if MIME type is not in the allowed list.
}
unlink($file);

Check if a file is writable.

$file = 'config.ini';
file_put_contents($file, '[settings]');
try
{
    // Asserts the file exists, is readable, and is writable.
    assertFile($file, null, true, true);
}
catch (FileException $e)
{
    // Throws an exception if file is not writable.
}
unlink($file);
author

Marc Alcaraz (ekameleon)

since
1.0.0

        
On this page

Search results