Search code examples
phpazureazure-storage

Create Path at Microsoft Azure with PHP


Im building an application where I need to dynamically create some directories using the Azure's PHP SDK.

I did it using a loop but Im unsure if thats the correct way of doing it so heres my code;

I cant create a path that already exists so I have to check level by level if a directory and exists, than enters it and repeat.

public function generateDirectory($path)
{
    $pathArray = explode("/", $path);

    $currentPath = "";
    try {
        foreach ($pathArray as $key => $slice) {
            $directories = $this->fileClient->listDirectoriesAndFiles("abraco", $currentPath)->getDirectories();
            $currentPath .= $slice . "/";
            $exists = false;
            foreach ($directories as $key => $directory) {
                if ($directory->getName() === $slice) {
                    $exists = true;
                    break;
                }
            }
            if (!$exists) {
                $this->fileClient->createDirectory("abraco", $currentPath);
            }

        }
        return true;
    } catch (Exception $e) {
        return false;
    }

}

Doesnt it should have a method to create a full path with subfolders? I think that this way is not performatic.


Solution

  • Doesnt it should have a method to create a full path with subfolders? I think that this way is not performatic.

    I agree with you that there is a method to create a full path with subfolders will be better. But currently, as you metioned that if we want to create full path with subfolders, we need to create the directory folder level by level.

    If you use fiddler to capture request while you create multi-level directory structure via PHP SDK,you could find it use the following Rest API

    https://myaccount.file.core.windows.net/myshare/myparentdirectorypath/mydirectory?
    restype=directory
    

    For more information please refer to Azure file Storage Create directory API.

    myparentdirectorypath Optional. The path to the parent directory where mydirectory is to be created. If the parent directory path is omitted, the directory will be created within the specified share.

    If specified, the parent directory must already exist within the share before mydirectory can be created.