Oihana PHP

makeDirectory.php

Table of Contents

Functions

makeDirectory()  : string|null
Creates a directory if it does not exist and returns the path of the directory.

Functions

makeDirectory()

Creates a directory if it does not exist and returns the path of the directory.

makeDirectory(string|null $directory[, int $permissions = 0755 ][, bool $recursive = true ]) : string|null
Parameters
$directory : string|null

The path of the directory to create.

$permissions : int = 0755

The permissions to set for the directory (default: 0755).

$recursive : bool = true

If true, creates parent directories as needed (default: true).

Tags
throws
DirectoryException

If the directory cannot be created.

example

Basic usage: create a directory if it does not exist.

use function oihana\files\makeDirectory;

$dir = 'cache/files';
try
{
    makeDirectory($dir);
    echo "Directory created or already exists: $dir";
}
catch ( DirectoryException $e )
{
    // Handle error
}

Create a directory with custom permissions:

try
{
    makeDirectory('data/output', 0777);
}
catch ( DirectoryException $e )
{
    // Handle permission or creation error
}

Create a nested directory with recursive option:

try
{
    makeDirectory('var/log/myapp/debug', 0755, true); // parent folders created
}
catch ( DirectoryException $e )
{
    // Handle error
}

Handle failure when directory path is invalid or not writable:

try
{
   makeDirectory(''); // Throws exception: empty path
}
catch (DirectoryException $e)
{
    echo $e->getMessage(); // Directory path cannot be null or empty.
}

Check if the returned path is usable:

$path = makeDirectory('tmp/test');
file_put_contents( $path . '/sample.txt', 'content' ) ;
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string|null

Returns the path of the directory.


        
On this page

Search results