Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

19.11. Removing a Directory and Its Contents

Problem

You want to remove a directory and all of its contents, including subdirectories and their contents.

Solution

On Unix, use rm:

$directory = escapeshellarg($directory);
exec("rm -rf $directory");

On Windows, use rmdir:

$directory = escapeshellarg($directory);
exec("rmdir /s /q $directory");

Discussion

Removing files, obviously, can be dangerous. Be sure to escape $directory with escapeshellarg( ) so that you don’t delete unintended files.

Because PHP’s built-in directory removal function, rmdir( ) , works only on empty directories, and unlink( ) can’t accept shell wildcards, calling a system program is much easier than recursively looping through all files in a directory, removing them, and then removing each directory. If an external utility isn’t available, however, you can modify the pc_process_dir( ) function from Recipe 19.10 to remove each subdirectory.

See Also

Documentation on rmdir( ) at http://www.php.net/rmdir; your system’s rm or rmdir documentation, such as the Unix rm(1) manpage or the Windows rmdir /? help text.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata