473,394 Members | 1,869 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

deleting all the files in a directory

Hello,

Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?

Thanks for your help, - Dave

Feb 13 '06 #1
19 2273
NC
laredotorn...@zipmail.com wrote:

Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?


One, if you are willing to live with an OS-dependent solution. You can
read your OS manual for the command that removes files (rm on Unix or
del on Windows), figure out what comand-line keys are necessary to
remove all files in a given directory, and pass the respective command
to your operating system via exec(), passthru(), or system().

Cheers,
NC

Feb 13 '06 #2
la***********@zipmail.com wrote:
Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?


<?php $ret = `cd $mydir && rm -fr *`; ?>

--
E. Dronkert
Feb 13 '06 #3
On 13 Feb 2006 12:14:40 -0800, la***********@zipmail.com wrote:
Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?


$dir = '/x/y/z';
if ($dir = opendir($dir))
{
while (($file = readdir($dir)) !== false)
{
if (is_file("$dir/$file"))
{
unlink("$dir/$file");
}
}
}

If you really want it shorter you can remove some of the braces.

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Feb 13 '06 #4
Andy Hassall wrote:
if (is_file("$dir/$file"))


You're potentially missing (symbolic) links and files larger than
int-size. Better to check for '.' or '..' filenames. Clumsy, I know.

--
E. Dronkert
Feb 13 '06 #5
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ewoud Dronkert wrote:
<?php $ret = `cd $mydir && rm -fr *`; ?>


I can halve that:

<?`rm -rf $mydir/*`;?>

- --
- ----------------------------------
Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

http://acm.asoc.fi.upm.es/~mr/
Proudly running Debian Linux with 2.6.12-1-686 kernel, KDE3.5.0, and PHP
5.1.2-1 generating this signature.
Uptime: 23:58:50 up 2:28, 1 user, load average: 0.49, 0.75, 0.51

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFD8Q/73jcQ2mg3Pc8RAqTyAJ4t6X+yGGbRpNAMfdpMBW/tG9ciLACfYRdK
d6NfQdNGlgZAZWBJqhP/Ybg=
=ttCu
-----END PGP SIGNATURE-----
Feb 13 '06 #6
On Mon, 13 Feb 2006 22:47:26 +0100, Ewoud Dronkert
<fi*******@lastname.net.invalid> wrote:
Andy Hassall wrote:
if (is_file("$dir/$file"))
You're potentially missing (symbolic) links


Missing, or including? symlinks to files return true from is_file() if their
target is a file, so yes, that should probably have a && !is_link() condition
as well, depending on what the OP really wants deleted.
and files larger than int-size.


Hm, didn't know about that one. http://bugs.php.net/bug.php?id=27792

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Feb 13 '06 #7
Andy Hassall wrote:
Missing, or including? symlinks to files return true from is_file() if their
target is a file, so yes, that should probably have a && !is_link() condition
as well, depending on what the OP really wants deleted.


My guess is, not that but || is_link().

--
E. Dronkert
Feb 14 '06 #8

"Andy Hassall" <an**@andyh.co.uk> wrote in message
news:6h********************************@4ax.com...
On 13 Feb 2006 12:14:40 -0800, la***********@zipmail.com wrote:
Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?

this works for one directory, but not subdirectories under it. for that, it
needs to be recursive.

function zapdir($dir) {
if ($dir = opendir($dir)) {
while (($file = readdir($dir)) !== false) {
if (is_file("$dir/$file")) {
unlink("$dir/$file");
}
//is a directory or a symlink
if (is_dir("$dir/$file") && "." != $file && ".." != $file) {
zapdir("$dir/$file");
rmdir("$dir/$file") or echo "unable to remove directory
$dir/$file\n";
}
if (is_link("$dir/$file")) {
unlink("$dir/$file"); //remove symbolic link. does not
remove original file AFAIK
}
}
}
}
zapdir('/x/y/z');

If you really want it shorter you can remove some of the braces.
--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool

Feb 14 '06 #9
d
"Jim Michaels" <jm******@nospam.yahoo.com> wrote in message
news:kZ********************@comcast.com...

"Andy Hassall" <an**@andyh.co.uk> wrote in message
news:6h********************************@4ax.com...
On 13 Feb 2006 12:14:40 -0800, la***********@zipmail.com wrote:
Using PHP 4, what are the shortest amount of lines I can write to
delete all the files in a given directory?

this works for one directory, but not subdirectories under it. for that,
it needs to be recursive.

function zapdir($dir) {
if ($dir = opendir($dir)) {
while (($file = readdir($dir)) !== false) {
if (is_file("$dir/$file")) {
unlink("$dir/$file");
}
//is a directory or a symlink
if (is_dir("$dir/$file") && "." != $file && ".." != $file) {
zapdir("$dir/$file");
rmdir("$dir/$file") or echo "unable to remove directory
$dir/$file\n";
}
if (is_link("$dir/$file")) {
unlink("$dir/$file"); //remove symbolic link. does not
remove original file AFAIK
}
}
}
}
zapdir('/x/y/z');


That will run out of stack space in large directory trees... Best to close
the $dir before calling zapdir...
If you really want it shorter you can remove some of the braces.

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool


Feb 14 '06 #10
On Mon, 13 Feb 2006 22:47:26 +0100, Ewoud Dronkert wrote:
You're potentially missing (symbolic) links and files larger than
int-size. Better to check for '.' or '..' filenames. Clumsy, I know.


This will work better:

foreach (glob("/mydir/*") as $f) {
filetype($f)== 'file' ? unlink($f) : null;
}

If my coding style betrays using some other scripting languages
as well, I cannot help it. In some other scripting languages that
might have been coded like this:

foreach (glob "/mydir/*") {
unlink($_) if -f $_;
}

As I don't have "suffix if" in PHP, I came up with the ternary operator.
Note that I could have written '' instead of "null" and still have the
same effect. Of course, I cannot rewrite something like this:

map { unlink($_) if -f $_; } glob("/mydir/*");

--
http://www.mgogala.com

Feb 15 '06 #11
On Mon, 13 Feb 2006 21:34:28 +0100, Ewoud Dronkert wrote:
<?php $ret = `cd $mydir && rm -fr *`; ?>


That will be a little harder on a Windows system.

--
http://www.mgogala.com

Feb 15 '06 #12
On Mon, 13 Feb 2006 21:14:36 +0000, Andy Hassall wrote:
if ($dir = opendir($dir))
{
while (($file = readdir($dir)) !== false)


PHP supports globs, just as Perl does.

--
http://www.mgogala.com

Feb 15 '06 #13
Mladen Gogala wrote:
PHP supports globs, just as Perl does.


Yeah, I'm always forgetting. Thanks.

--
E. Dronkert
Feb 15 '06 #14

Mladen Gogala wrote:
map { unlink($_) if -f $_; } glob("/mydir/*");


Speaking of this, is there any chance of references to functions in
PHP?
The "{ unlink($_) if -f $_; }" part of the code here is so called
"anonymous
subroutine" or "subroutine reference" which is sort of convenient if
you don't
want to clutter the namespace with unneeded function names. All you
need
to be able to implement your one-liner in PHP is an anonymous function
reference
to pass to array_walk, which is identical to Perl's "map".
Also, Perl has qr() construct which compiles regular expressions and
makes
things significantly faster. Is there any flag to compile regular
expression in
prreg_match? The only documented flag here is to capture offset. If I
need to
go through multiple lines in a loop, will PHP compile the regular
expression?
The situation I have in mind is something like this:

while ( $line=fread($file,128)) {
if preg_match("/$regexp/",$line,$found)....
}

As you can see, I'm a beginner with PHP. I have 5 years or so
experience
with Perl.

Feb 15 '06 #15
On 15 Feb 2006 12:23:33 -0800, "Bart the bear" <ba*********@gmail.com> wrote:
Speaking of this, is there any chance of references to functions in
PHP?
The closest is create_function() which isn't as good as Perl's ability to pass
code blocks, as you have to embed the anonymous function source in a string.

http://uk2.php.net/create_function
Also, Perl has qr() construct which compiles regular expressions and
makes
things significantly faster. Is there any flag to compile regular
expression in
prreg_match?


Looking at the PHP source code, at least for PHP 5.1.2, it already compiles
expressions on first use and keeps the results in a cache - subsequent calls
use the cached compiled version. At least from a quick inspection of
ext/pcre/php_pcre.c, e.g. line 438, within php_pcre_match:

/* Compile regex or get it from cache. */
if ((re = pcre_get_compiled_regex(regex, &extra, &preg_options
TSRMLS_CC)) == NULL) {
RETURN_FALSE;
}

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Feb 15 '06 #16
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Mladen Gogala wrote:
On Mon, 13 Feb 2006 21:34:28 +0100, Ewoud Dronkert wrote:
<?php $ret = `cd $mydir && rm -fr *`; ?>


That will be a little harder on a Windows system.


Do you mean that <?php `rmdir /s $mydir`;?> is harder than that?

;-)

- --
- ----------------------------------
Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

http://acm.asoc.fi.upm.es/~mr/
Proudly running Debian Linux with 2.6.12-1-686 kernel, KDE3.5.0, and PHP
5.1.2-1 generating this signature.
Uptime: 00:39:22 up 3:05, 1 user, load average: 0.72, 0.86, 0.87

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFD87ve3jcQ2mg3Pc8RAqufAJ9qF0r4Fqx/VN7EUskZrDfDS7CF0QCfQ2Nw
64mLfpvArvtxz6G4A+teZT0=
=YWuT
-----END PGP SIGNATURE-----
Feb 16 '06 #17
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Bart the bear wrote:
Speaking of this, is there any chance of references to functions in
PHP?


Aside from lambda-style functions (see create_function()), you can reference
a function by its name:

<?php

function foo()
{
echo "wow!";
}

$bar = 'foo';

$bar();

?>
- --
- ----------------------------------
Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

No intentes doblar la cuchara, eso es imposible; simplemente intenta
comprender la verdad: que no hay cuchara
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFD87xl3jcQ2mg3Pc8RAr+qAJ4lnXEtiyUKXV3lOcxBTP w+Ci/zggCfUnw/
9qdZI2sdFjJ9lNOx5CcrFAY=
=PhXF
-----END PGP SIGNATURE-----
Feb 16 '06 #18
On Wed, 15 Feb 2006 21:18:58 +0000, Andy Hassall wrote:
The closest is create_function() which isn't as good as Perl's ability to pass
code blocks, as you have to embed the anonymous function source in a string.
Yes, but it is still much more cumbersome then Perl mechanism of
references. Quite frankly, the only thing that references are really
needed for is to model self-referential structures like doubly linked
lists and alike. Personally, I find "foreach" version much more
understandable then "map" version. Speaking of Perl, I have my
own personal style of coding. My former boss, now my friend finds
Perl idioms like:

$a ||= "default";

repugnant and disgusting. He will always write the same thing
like this:

if (!defined($a)) {
$a="default";
}

PHP doesn't allow the 1st form and that is a good thing because the
||= version is the best way to write an obfuscated code which will be
misunderstood by the maintainer coming after the author. One frequent
version of the code above is

bless $var1 ref($_[0])||$_[0];

which is something that will scare away anybody who dreams of
learning Perl. I believe that not being able to write things
as concisely as in Perl is not necessarily a bad thing. Emulating
obfuscating loops by "map" function and an anonymous references
is not something that should be hastily implemented. If you want
to learn PHP, it is an order of magnitude easier to learn then
Perl.

Here I am running a risk to turn this thread into a religious war
between PHP and Perl fans. That is not my intention, I use both as,
I believe, you do as well. Both languages have their strengths and
weaknesses. I find them well complementing each other. Perl has
a PHP module, containing many of the much coveted PHP functions,
while PHP has PECL Perl module which makes it possible to run
Perl scripts from PHP. No need for religious war from either side.

http://uk2.php.net/create_function
Also, Perl has qr() construct which compiles regular expressions and
makes
things significantly faster. Is there any flag to compile regular
expression in
prreg_match?


Looking at the PHP source code, at least for PHP 5.1.2, it already compiles
expressions on first use and keeps the results in a cache - subsequent calls
use the cached compiled version. At least from a quick inspection of
ext/pcre/php_pcre.c, e.g. line 438, within php_pcre_match:

/* Compile regex or get it from cache. */
if ((re = pcre_get_compiled_regex(regex, &extra, &preg_options
TSRMLS_CC)) == NULL) {
RETURN_FALSE;
}


This I didn't know. Thanks for the info.
--
http://www.mgogala.com

Feb 16 '06 #19
On 2006-02-15, Mladen Gogala <go****@sbcglobal.net> wrote:
On Mon, 13 Feb 2006 21:34:28 +0100, Ewoud Dronkert wrote:
<?php $ret = `cd $mydir && rm -fr *`; ?>


That will be a little harder on a Windows system.


not really.

<?php $ret=`deltree $mydir\\*.*` ; ?>

--

Bye.
Jasen
Feb 16 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Guinness Mann | last post by:
Greetings, I can't figure out what to search on to find the documentation on how to completely delete a "solution" from VS.NET 2003. I have no problem at all deleting projects, but even if I...
5
by: Rosa | last post by:
Hi, I'm trying to clear the TIF on Windows XP programmatically with the below code. This code works fine on any folder but the TIF. For some reason the atEnd() statements always defaults to true...
1
by: John | last post by:
Hi How can I delete all files within a particular folder, in asp.net (vb)? Thanks Regards
6
by: Martin Bischoff | last post by:
Hi, I'm creating temporary directories in my web app (e.g. ~/data/temp/temp123) to allow users to upload files. When I later delete these directories (from the code behind), the application...
4
by: clintonG | last post by:
I started an application using Beta2 and now I've been having a variety of problems continuing to develop the application in 2.0 that I suspect may be related to left-over icky stuff. What can I...
1
by: Lee | last post by:
Hi, when deleting a directory using;- string dir = "whatever"; Directory.Delete(dir); it fails if files/directories exist within the directory being deleted. is there an easy way of...
2
by: vikram.lakhotia | last post by:
Hi Have you tried deleting a directory in Asp.Net. Here is an article discussing the problem deleting a Directory in Asp.Net http://www.vikramlakhotia.com/Deleting_Directory_in_ASPnet_20.aspx...
4
by: RKalai | last post by:
Hi I am moving list of files from one directory to another directory.i am doing it by first moving all the files from the source directory to destination directory using filecopy command.then...
3
by: Kimera.Kimera | last post by:
I'm trying to write a program in VB.net 2003 that basically deletes all files, folders, sub-folders and sub-sub folders (etc). The program is simply for deleting the Windows/Temp folder contents,...
12
Nepomuk
by: Nepomuk | last post by:
Hi! I want to have my program delete some folders including all contents. For that, I wrote this method: private static void delete(String source) { File tmp = new File(source);...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.