There must be a better way (to clean a filename)
| From: | Verdon Vaillancourt | Date: | Sun, 11 May 2003 00:43:29 +0000 |
| Subject: | There must be a better way (to clean a filename) | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-147175@lists.php.net to get a copy of this message | ||
Pretty much a newbie question...
The following lines have been copied from examples I've looked at and are
part of a bigger function I am attempting to write, that uploads a file to
the server and then does some db work. The purpose of the following lines
are to get a 'clean' name for the uploaded file that is then used for other
tasks later on.
What I mean by 'clean' is that if a user were to upload a file named
something silly like "User's Uploaded fiLe.jpg", I'll end up with
"user_s_uploaded_file.jpg" The following lines actually return
"user_s_uploaded_file_jpg.jpg" which is OK but could be better.
I understand what is happening, and I've tried a few variations to the
ereg_replace to get it to leave the period alone (so I don't have to put the
extension back on) but haven't had any success. Would anyone care to suggest
the right expression, or an overall better way I could/should handle
something like this?
$realname = strtolower($HTTP_POST_FILES['userfile']['name']);
$extension = substr(strrchr($realname,"."),1);
// remove %20 and the like from name
$realname = urldecode($realname);
// replace multiple non-word characters with a single "_"
$cleanedFilename = ereg_replace("[^[:alnum:]]", "_", $realname);
// Get rid of extra underscores
$cleanedFilename = ereg_replace("_+", "_", $cleanedFilename);
$cleanedFilename = ereg_replace("(^_|_$)", "", $cleanedFilename);
// The final name
$save_name = "$cleanedFilename"."."."$extension"
TIA, verdon