I suggest the the following, and only the following method:
<?
$dir = 'my/base/path/';
$file = $dir . $userSelectedFilename;
if(strpos(realpath($file),realpath($dir)) === 0) && is_file($file)) { // beware of the three ===
unlink($file);
}
Why?
It is safe to rely on realpath to find out the real location of a file which eliminates directory traversal / multibyte double-dots etc.
After that we check whether the beginning of the reapath of the file is really the beginning of our expacted directory (strpos).
After that we also check whether the file is really a file and not some symlink pointing elswhere or something like that.
I have seen character eliminating solutions been broken by multibyte strings and similar attacks.
This method so far far withstands all of these.