9

I'm working on a php script, where I want to delete some files from a given folder using wildcard (*).
I've found some working examples like this one, where unlink() and glob() function are used.

Now, i was wondering, would it also be ok to delete the files using the exec function and a command like rm -f /path/to/folder/_prefix_* ?
Are there any security risks taken using this?
And if it is ok, would it be better in terms of performance?

EDIT:
So, from the first answers i can see that indeed, using exec could be an acceptable solution.
What about performance issues? Is there any chance the exec option could be better (faster/less demanding) over the glob/unlink technique?

Thank you in advance

Community
  • 1
  • 1
CdB
  • 4,738
  • 7
  • 46
  • 69
  • 1
    rm would be fine, security issues depends on who can run the script. –  Sep 03 '12 at 21:49

2 Answers2

15

Because there is no chance for user-supplied data to be injected, there is no security issue in using exec over glob/unlink. However, using glob/unlink allows you to define exceptions:

foreach(glob("delete/*") as $f) {
    if( $f == "delete/notme.txt") continue;
    unlink($f);
}

And exec is often disabled on shared servers so glob/unlink is more portable. If you have a dedicated setup and don't intend on giving it up, you don't need to worry about that.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks for replying Kolink. I'm on an owned server, and exec is enabled and working fine. Do you think it could make difference in performance using one technique over the other? – CdB Sep 03 '12 at 21:56
  • I would imagine `exec` is faster, but `glob/unlink` lets the script know at all times exactly what is going on - useful for console applications more than web-based, but you can also get an error report for each file, or list the deleted files... – Niet the Dark Absol Sep 03 '12 at 21:58
2

Both options could be fine. However, if you not control your own server or are on shared hosting, the exec command could not be available.

To be on the save side, use glob and unlink.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55