Oihana PHP

assertFile.php

Table of Contents

Functions

assertFile()  : void
Asserts that a file exists and is accessible.

Functions

assertFile()

Asserts that a file exists and is accessible.

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

The path of the file to check.

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

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

$isWritable : bool = false

Whether to assert that the directory 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