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(null|array<string|int, mixed>|string $pathOrOptions[, int $permissions = 0755 ][, bool $recursive = true ][, string|null $owner = null ][, string|null $group = null ]) : string|null
Parameters
$pathOrOptions : null|array<string|int, mixed>|string

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).

$owner : string|null = null

User name or ID to set as directory owner (optional).

$group : string|null = null

Group name or ID to set as directory group (optional).

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' ) ;

Assign an user/group permissions :

makeDirectory('/var/www/mydir', 0775, true, 'www-data', 'www-data');

Use an associative array to creates the new directory

makeDirectory
([
    'path'        => '/var/www/mydir',
    'permissions' => 0775,
    'recursive'   => true,
    'owner'       => 'www-data',
    'group'       => 'www-data',
]);
author

Marc Alcaraz (ekameleon)

since
1.0.0
see
MakeDirectoryOption
Return values
string|null

Returns the path of the directory.


        
On this page

Search results