note 85830 deleted from function.mime-content-type by philip

From: Date: Thu, 03 Sep 2015 02:34:44 +0000
Subject: note 85830 deleted from function.mime-content-type by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203601@lists.php.net to get a copy of this message
Note Submitter: Curtiss ---- I'm not sure if anyone is still using the functions shown below (I'm guessing someone must still be, since the latest update to the functions was made a few months ago), but I think you'd be better off using an explode statement rather than the regex shown in most of the functions to find the filesuffix. The regex shown is only going to catch files with extensions between 2 and 4 characters. While filenames with more or less than that are extremely rare, they do exist. If you open the regex up to start accepting those types of things, however, you're making your life complicated for no reason. In addition, I don't see the need for the overhead produced by the preg_match function when you could just use the explode and array_pop functions together. If you explode the filename, using the dot as a separator, you can simply pop the last element off of the array to get the real file extension, no matter how short or long it is, without the overhead of a regex (unless one of those functions calls a regex in the background of which I'm not aware). Therefore, where the regex would return no results on something like: /var/www/html/example.backup or /var/www/html/example-program.c the explode function would simply split it wherever it finds a dot and you can pop the last one off: <?php $filename = '/var/www/html/example.backup'; $finfo = explode('.',$filename); $fileSuffix = array_pop($finfo); ?> Then, to put the rest of the file name back together, you can use the implode function on the remainder of the finfo array. Alternatively, when putting the rest of the file name back together, you could use the str_replace function to replace the dot and the extension with nothing, but then you run the rare risk of removing the same string from the middle of the file name somewhere (not very likely, but possible nonetheless). Also, on a side note, the last function example is going to return the wrong value if the file extension is not in the list and the mime_content_type function exists. Because that part of the function re-sets the $fileSuffix variable, without returning a value, the function is going to move on to the next statement, which is only going to return the first letter of whatever was returned by the mime_content_type function. Instead of reading: <?php if(function_exists("mime_content_type")) { $fileSuffix = mime_content_type($filename); } ?> it should read: <?php if(function_exists("mime_content_type")) { return mime_content_type($filename); } ?>

« previous php.notes (#203601) next »