I'm not sure whether your regex will really help: There are valid characters outside that range that you won't be able to delete this way.
One thing that I would do is do a realpath()
on the full final path, and check whether it still is a child of your allowed file path. That will prevent ../../
directory traversal attacks, even if they use some special characters. That should already provide fairly good security.
You could also additionally scan the directory using glob()
and check the results to see whether the requested file is actually in there (that is impossible to circumvent even with the most sneaky directory traversal.)
If you want to be totally paranoid about this, you could use a different approach altogether: Don't transfer file names, but list indexes of a list that you specified before. If for example you show this list to the user and save it in a temporary text file or database record:
- Readme.txt
- License
- Readme.doc
and then pass only the (random) ID of the text file or database record, and the number of the file you want to delete:
delete.php?list=xasdafdas&index=3
you should have a solution that is pretty invulnerable against any conceivable kind of injection and file name tampering.
You would have to store an individual list for every request, as the files can change.