PHP: Hypertext Preprocessor (2024)

set_file_buffer »

« rewind

  • Посібник з PHP
  • Довідник функцій
  • Розширення для роботи з файловою системою
  • Filesystem
  • Функції Файлової Системи

(PHP 4, PHP 5, PHP 7, PHP 8)

rmdirRemoves directory

Опис

rmdir(string $directory, ?resource $context = null): bool

Attempts to remove the directory named by directory. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Параметри

directory

Path to the directory.

context

resourceконтекст потоку.

Значення, що повертаються

Повертає true у разі успіху або false в разі помилки.

Приклади

Приклад #1 rmdir() example

<?php
if (!is_dir('examples')) {
mkdir('examples');
}
rmdir('examples');
?>

Прогляньте також

  • is_dir() - Tells whether the filename is a directory
  • mkdir() - Makes directory
  • unlink() - Deletes a file

+add a note

User Contributed Notes 29 notes

up

down

207

nbari at dalmp dot com

11 years ago

Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?php
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach (
$files as $file) {
(
is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return
rmdir($dir);
}
?>

up

down

37

itay at itgoldman dot com

9 years ago

some implementations of recursive folder delete don't work so well (some give warnings, other don't delete hidden files etc).

this one is working fine:
<?phpfunction rrmdir($src) {
$dir = opendir($src);
while(
false !== ( $file = readdir($dir)) ) {
if ((
$file != '.' ) && ( $file != '..' )) {
$full = $src . '/' . $file;
if (
is_dir($full) ) {
rrmdir($full);
}
else {
unlink($full);
}
}
}
closedir($dir);
rmdir($src);
}
?>

up

down

47

info at top-info dot org

14 years ago

The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy...

up

down

36

dj dot thd at hotmail dot com

8 years ago

Never ever use jurchiks101 at gmail dot com code!!! It contains command injection vulnerability!!!
If you want to do it that way, use something like this instead:

<?php
if (PHP_OS === 'Windows')
{
exec(sprintf("rd /s /q %s", escapeshellarg($path)));
}
else
{
exec(sprintf("rm -rf %s", escapeshellarg($path)));
}
?>

Note the escapeshellarg usage to escape any possible unwanted character, this avoids putting commands in $path variable so the possibility of someone "pwning" the server with this code

up

down

44

holger1 at NOSPAMzentralplan dot de

14 years ago

Another simple way to recursively delete a directory that is not empty:

<?php
function rrmdir($dir) {
if (
is_dir($dir)) {
$objects = scandir($dir);
foreach (
$objects as $object) {
if (
$object != "." && $object != "..") {
if (
filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>

up

down

14

wolfoneil at gmx.de

9 years ago

I was working on some Dataoperation, and just wanted to share an OOP method with you.

It just removes any contents of a Directory but not the target Directory itself! Its really nice if you want to clean a BackupDirectory or Log.

Also you can test on it if something went wrong or if it just done its Work!

I have it in a FileHandler class for example, enjoy!

<?php public function deleteContent($path){
try{
$iterator = new DirectoryIterator($path);
foreach (
$iterator as $fileinfo ) {
if(
$fileinfo->isDot())continue;
if(
$fileinfo->isDir()){
if(
deleteContent($fileinfo->getPathname()))
@
rmdir($fileinfo->getPathname());
}
if(
$fileinfo->isFile()){
@
unlink($fileinfo->getPathname());
}
}
} catch (
Exception $e ){
// write log
return false;
}
return
true;
}
?>

up

down

6

steffen at wirsching-idstein dot de

14 years ago

Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir(opendir($dirname)); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.

up

down

8

Anonymous

7 years ago

itay at itgoldman's function falls into an infinite loop if the $src directory doesn't exist.
Here's a fix - one should do at least a file_exists() check before the loop:

function rrmdir($src) {
if (file_exists($src)) {
$dir = opendir($src);
while (false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
$full = $src . '/' . $file;
if (is_dir($full)) {
rrmdir($full);
} else {
unlink($full);
}
}
}
closedir($dir);
rmdir($src);
}
}

Thanks to itay for the original function, though, it was helpful.

up

down

6

shane dot ray87 at gmail dot com

12 years ago

This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors. I was not able to delete them with PHP or in windows itself. The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own. Disabling the wincachce module resolved the issue.

Hope this helps.

up

down

5

Chris Wren

11 years ago

I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.

up

down

5

thomas

12 years ago

Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle)) {...

if a folder named 0 (zero) is found during traversing the hierarchy

up

down

13

lprent at primary dot geek dot nz

10 years ago

It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

<?php
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach (
$files as $file) {
(
is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return
rmdir($dir);
}
?>

up

down

5

tuxedobob

10 years ago

Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec('rmdir folder-to-delete /s /q'); //windows
exec('rmdir -rf folder-to-delete'); //OS X/*nix?

up

down

4

ahmadmarafa at gmail dot com

9 years ago

function unlinkDir($dir)
{
$dirs = array($dir);
$files = array() ;
for($i=0;;$i++)
{
if(isset($dirs[$i]))
$dir = $dirs[$i];
else
break ;

if($openDir = opendir($dir))
{
while($readDir = @readdir($openDir))
{
if($readDir != "." && $readDir != "..")
{

if(is_dir($dir."/".$readDir))
{
$dirs[] = $dir."/".$readDir ;
}
else
{

$files[] = $dir."/".$readDir ;
}
}
}

}

}

foreach($files as $file)
{
unlink($file) ;

}
$dirs = array_reverse($dirs) ;
foreach($dirs as $dir)
{
rmdir($dir) ;
}

}

up

down

2

mmaksh*ta2398 at gmail dot com

5 years ago

it Will Delete All Fildes in folder and that folder too...

echo $path = 'D:\xampp\htdocs\New folder\New folder';

function rmdir_recursive($dir) {
$it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($it as $file) {
if ($file->isDir()) rmdir($file->getPathname());
else unlink($file->getPathname());
}
rmdir($dir);
}
rmdir_recursive($path);

up

down

3

rn at clubfl dot com

16 years ago

I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO... if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.

up

down

4

omikrosys at gmail dot com

14 years ago

Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'.

up

down

2

Baraka Mghumba

9 years ago

Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
{
if (is_dir($dir))
{
$files = scandir($dir);
foreach ($files as $file)
{
if ($file != "." && $file != "..")
{
if (filetype($dir."/".$file) == "dir")
{
$this->deletedir($dir."/".$file);
}
else
{
unlink($dir."/".$file);
}
}
}
reset($objects);
if(rmdir($dir))
{
return 'deleted successfully!';
}
else
{
return 'delete failed!';
}
}
else
{
return 'doesn\'t exist or inaccessible!';
}
}
Something to note:
You have to take care of file permission if necessary

up

down

4

asn at asn24 dot dk

15 years ago

A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory($dir) {
if (!
file_exists($dir)) return true;
if (!
is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (
scandir($dir) as $item) {
if (
$item == '.' || $item == '..') continue;
if (!
deleteDirectory($dir . "/" . $item)) {
chmod($dir . "/" . $item, 0777);
if (!
deleteDirectory($dir . "/" . $item)) return false;
};
}
return
rmdir($dir);
}
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]

up

down

1

O S

14 years ago

This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll($directory, $empty = false) {
if(
substr($directory,-1) == "/") {
$directory = substr($directory,0,-1);
}

if(!

file_exists($directory) || !is_dir($directory)) {
return
false;
} elseif(!
is_readable($directory)) {
return
false;
} else {
$directoryHandle = opendir($directory);

while (

$contents = readdir($directoryHandle)) {
if(
$contents != '.' && $contents != '..') {
$path = $directory . "/" . $contents;

if(

is_dir($path)) {
deleteAll($path);
} else {
unlink($path);
}
}
}
closedir($directoryHandle);

if(

$empty == false) {
if(!
rmdir($directory)) {
return
false;
}
}

return

true;
}
}
?>

up

down

1

samy dot see at gmail dot com

13 years ago

if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

<?php
if(file_exists($path.'/Thumbs.db')){
unlink($path.'/Thumbs.db');
}
?>

and then

<?php rmdir($path); ?>

up

down

dev dot abi dot log at gmail dot com

1 year ago

a simple snipped for removing empty dirs recursive :

<?php
function removeEmptyDirs($fullPath)
{
if(!
is_dir($fullPath)){
return;
}
$children = array_diff(scandir($fullPath), ['.','..']);

foreach(

$children as $child){
removeEmptyDirs($fullPath. $child. DIRECTORY_SEPARATOR);
}
$children = array_diff(scandir($fullPath), ['.','..']);
if(empty(
$children)){
echo
"the $fullPath empty directory has been removed.\n";
rmdir($fullPath);
}
}
?>

up

down

anonymous_user

3 years ago

// Recursive PHP function to completely remove a directory

function delete_directory_recursively( $path ) {

$dir = new \DirectoryIterator( $path );

// Iterate through the subdirectories / files of the provided directory
foreach ( $dir as $dir_info ) {

// Exclude the . (current directory) and .. (parent directory) paths
// from the directory iteration
if ( ! $dir_info->isDot() ) {

// Get the full currently iterated path
$iterated_path = $dir_info->getPathname();

// If the currently iterated path is a directory
if ( $dir_info->isDir() ) {

// which is not empty (in which case scandir returns an array of not 2 (. and ..) elements)
if ( count( scandir( $iterated_path ) ) !== 2 ) {

// Call the function recursively
self::remove_directory_recursively( $iterated_path );

} else {

// if the currently iterated path is an empty directory, remove it
rmdir( $iterated_path );

}

} elseif ( $dir_info->isFile() ) {

// If the currently iterated path describes a file, we need to
// delete that file
unlink( $iterated_path );

}

} // loop which opens if the currently iterated directory is neither . nor ..

} // end of iteration through directories / files of provided path

// After iterating through the subpaths of the provided path, remove the
// concerned path
rmdir( $path );

} // end of delete_directory_recursively() function definition

up

down

1

TrashF at taistelumarsu dot org

16 years ago

In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().

up

down

1

longears at BLERG dot gmail dot com

12 years ago

Concise way to recursively remove a directory:

<?php
# recursively remove a directory
function rrmdir($dir) {
foreach(
glob($dir . '/*') as $file) {
if(
is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}
?>

up

down

bcairns at gmail dot com

15 years ago

I wasn't having much luck with the recursive delete functions below, so I wrote my own:

<?php
// ensure $dir ends with a slash
function delTree($dir) {
$files = glob( $dir . '*', GLOB_MARK );
foreach(
$files as $file ){
if(
substr( $file, -1 ) == '/' )
delTree( $file );
else
unlink( $file );
}
rmdir( $dir );
}
?>

Simple. Works.

up

down

-1

kevin at web-power dot co dot uk

14 years ago

I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below

<?php
function delTree($dir) {
$files = glob( $dir . '*', GLOB_MARK );
foreach(
$files as $file ){
if(
substr( $file, -1 ) == '/' )
delTree( $file );
else
unlink( $file );
}

if (

is_dir($dir)) rmdir( $dir );

}

?>

up

down

-2

YAPs

8 years ago

This version delete tree

<?PHPif(!defined('DS'))define("DS",DIRECTORY_SEPARATOR);

function

delTree($folder,$del_root=true)
{
$folder=trim($folder,DS).DS;
$f=glob($folder.'*',GLOB_MARK);
if(
count($f)>0)
foreach(
$f as $e)
{
if(
is_dir($e))
delTree($e);
else
unlink($e);
}
if(
$del_root)
rmdir($folder);
if(!
file_exists($folder))
return
$folder." is deleted";
else
return
$folder." not deleted";
}
?>

up

down

-3

frederico05 dot figueira at gmail dot com

8 years ago

//This is one example to delete full directory with all files inside there

function delDir($path){
if(is_dir($path) == TRUE){
$rootFolder = scandir($path);
if(sizeof($rootFolder) > 2){
foreach($rootFolder as $folder){
if($folder != "." && $folder != ".."){
//Pass the subfolder to function
delDir($path."/".$folder);
}
}
//On the end of foreach the directory will be cleaned, and you will can use rmdir, to remove it
rmdir($path);
}
}else{
if(file_exists($path) == TRUE){
unlink($path);
}
}
}

+add a note

PHP: Hypertext Preprocessor (2024)

FAQs

Is PHP an acronym for Hypertext Preprocessor responses True True False? ›

PHP was originally an abbreviation of Personal Home Page, but it now stands for the recursive initialism PHP: Hypertext Preprocessor.

Why is PHP not used anymore? ›

While JavaScript nowadays can be used almost everywhere, PHP is still a back-end programming language for web development. It is not supposed to compete with other languages on a front-end side or in data science (like Python) or in... you name it.

Is PHP an acronym for Hypertext Preprocessor? ›

PHP is a self-referentially acronym for PHP: Hypertext Preprocessor. Original it supposedly meant personal home page. It is an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.

Why is PHP not called HPP? ›

when PHP created its name was personal home page, but now it is only Hypertext preprocessor. which means here hypertext means html and preprocessor means it processed before html. because it is a server site language, where as html is client side. html execute in browser and PHP in server.

Why is PHP called a Hypertext Preprocessor? ›

The term "Hypertext Preprocessor" says that PHP is meant to be used to process web pages or HTML (Hypertext Markup Language) documents. It can be used for many different purposes such as processing web forms, sending email, handling files, and interacting with a database such as MySQL.

Why PHP is recursive acronym? ›

Most recursive acronyms are recursive on the first letter, which is therefore an arbitrary choice, often selected for reasons of humour, ease of pronunciation, or consistency with an earlier acronym that used the same letters for different words, such as PHP, which now stands for "PHP: Hypertext Preprocessor", but was ...

Why is PHP losing popularity? ›

Most likely, the reason behind this shift is that WordPress is moving away from PHP towards JavaScript. According to Matt Mullenweg, the co-creator of WordPress and CEO of Automattic, the majority of new code in WordPress is JavaScript now. WordPress has always been the building block of PHP's popularity.

Why is PHP dying? ›

PHP itself is not particularly secure by design and so would quickly be outclassed in modern development. Compared to the new wave of languages like . NET Core and Java, these are built with security concerns in mind, making them difficult to learn, develop and support.

What is PHP being replaced by? ›

JavaScript. There are many people who consider JavaScript (JS) the best PHP alternative for web development. It is the most popular programming language in the world, being used not just for web but for mobile and desktop development as well, thanks to many powerful frameworks.

Who is the father of PHP? ›

Rasmus Lerdorf is often referred to as the "Father of PHP." He created PHP (Hypertext Preprocessor) in 1994, initially as a set of tools for tracking visits to his online resume. Over time, PHP evolved into a widely-used server-side scripting language, integral to web development and dynamic websites.

Does PHP stand for Python? ›

PHP is a scripting language for developing web applications. Python is a general-purpose programming language. PHP is a bit more challenging to learn than Python. You can easily learn Python.

What is PHP in simple word? ›

PHP (Hypertext Processor) is a general-purpose scripting language and interpreter that is freely available and widely used for web development. The language is used primarily for server-side scripting, although it can also be used for command-line scripting and, to a limited degree, desktop applications.

Why do developers not like PHP? ›

It's very easy to make bad and insecure code with PHP. But PHP is not a security hole or doomed to ugly code if you code properly. Developers hate PHP because you are more likely to get errors with a language that allows so much freedom.

Why PHP is not preferred? ›

PHP was not very good language 15-20 years ago. Inconsistent, slow, missing features, missing good quality frameworks, mising dev tools and ecosystem.

What is the issue with PHP? ›

Broken Syntax. Often problems with PHP code are cause by something very simple. Check your syntax and look for broken code highlighting (if your editor supports it).

PHP: Hypertext Preprocessor (PHP) - WebDev ...The University of Memphishttps://www.memphis.edu ›

PHP: Hypertext Preprocessor (PHP) Resources. PHP is a self-referentially acronym for PHP: Hypertext Preprocessor. Original it supposedly meant personal home pag...
PHP is a server side scripting language which originally stood for Personal Home Page and was created by Rasmus Lerdorf in 1994. It was never intended to be a f...
It was first called Personal Home Page by programmer Rasmus Lerdorf while writing code to maintain his own "personal home page." Later,some Isreali de...

What is the acronym for PHP programming language? ›

The acronym PHP was originally derived from Personal Home Page Tools, but it now stands for PHP: Hypertext Preprocessor, which the PHP Group's documentation describes as a "recursive acronym."

What does PHP stand for in HTML? ›

PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language.

What is the meaning of PHP? ›

PHP (recursive acronym for PHP: Hypertext Preprocessor ) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Is HTTP the same as PHP? ›

An HTTP request can be used for all kinds of things, although it is typically used to request that a server return HTML content that your web browser can then display. PHP is a programming language that runs on a web server. It can be used to modify that HTML content on the fly.

Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5429

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.