note 54726 modified in function.basename by cmb
| From: | cmb@php.net | Date: | Fri, 14 Oct 2016 17:32:02 +0000 |
| Subject: | note 54726 modified in function.basename by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206898@lists.php.net to get a copy of this message | ||
There is a real problem when using this function on *nix servers, since it does not handle Windows
paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to
handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses
basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My
Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be
the best, but it works):
<?php
$newfile = basename($filen);
if (strpos($newfile,'\\') !== false) {
$tmp = preg_split("[\\\]",$newfile);
$newfile = $tmp[count($tmp) - 1];
}
?>
$newfile will now contain only the file name and extension, even if the POSTed file name included a
full Windows path.
--was--
There is a real problem when using this function on *nix servers, since it does not handle Windows
paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to
handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses
basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My
Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be
the best, but it works):
<?php
$filen = stripslashes($_FILES['userfile']['name']);
$newfile = basename($filen);
if (strpos($newfile,'\\') !== false) {
$tmp = preg_split("[\\\]",$newfile);
$newfile = $tmp[count($tmp) - 1];
}
?>
$newfile will now contain only the file name and extension, even if the POSTed file name included a
full Windows path.
http://php.net/manual/en/function.basename.php