Clearing and Removing Directories - machitgarha/pusheh GitHub Wiki

CAUTION: Run all of the examples in this page, and generally, use all of the following methods at your own risk, as it may remove important directories, e.g. be careful if you are running these commands as root in Linux OS (I hope you don't use sudo).

Clearing a directory

Clearing a directory is the process of removing all of the contents inside the directory:

if (Pusheh::clearDir(__DIR__ . "/logs"))
    echo "Waiting for new logs...";
else
    echo "Uh-huh! Something went wrong!";

The above code will delete all of the files and directories inside logs directory, but it keeps logs directory itself.

Removing a directory

Instead of just clearing a directory, you can remove a directory completely:

$oldDocsDir = __DIR__ . "/old-docs";

Pusheh::removeDir($oldDocsDir, true);

// Clear syntax
Pusheh::removeDirRecursive($oldDocsDir);

The code above will remove the directory recursively, in both cases. It first clears the directory, and then, removes the main directory as well. If anything in the directory cannot be removed, then an exception will be thrown. Also, if requested directory to be removed doesn't exist, the method will return false, and in the case of no exceptions, it will return true.

Although it may be a good idea to remove a directory completely, but it may cause your work to be lost, if you didn't make a backup. In the cases you want to be more strict about removing directories, you can use the following method:

Pusheh::removeDir(__DIR__ . "docs");

Using above method, if the directory is not empty, then it will raise an exception and prevents from removing the directory. It will remove the directory only if it's empty.

Symbolic links

You can use soft links option in Pusheh::clearDir() and Pusheh::removeDirRecursive() methods. If it's enabled and if the selected directory to be operated is a symbolic link, then only the link will be removed. Otherwise, if you disable it, all of the contents inside the linked directory will be deleted. As an example of the later case, suppose symlink is a link to data directory; the following example will remove all of the contents inside data directory:

Pusheh::clearDir("symlink", true);

However, if one of the directory contents is a symbolic link, then it will be safely removed, unlike above. For instance, consider the following directory tree:

app
|---- bin
|---- etc
|---- src
|---- data
data
|---- thing
|---- stuff

What we know is that /app/data is a symbolic link of /data. Now, if you want to remove the /app directory completely, the following code will not remove the contents of the /data directory:

// This will keep /data contents unchanged
Pusheh::removeDirRecursive("/app", true);