Search code examples
phppreg-replaceuploadify

What is the business best practice on validating filename?


I have a "dilema" and wonder what is business best practice.

I'm using Uploadify to upload images. Now I need to validate the filename before saving the file.

I've looked at different solutions, but can't get down to one good solution.

Here are my criterias:

  • Filename must be all in lowercase
  • Filename can only contain charaters [a-z0-9_-]
  • I must be able to rename file

How would you go about if a filename is my.file(name).jpeg ?

I could explode the filename on '.' and save the extension, then implode to get the filename again. But not sure if that's the best soltion.

I have the following functions that helps a bit:

function getExts($filename) 
{ 
    $exts = explode("[/\\.]", $filename) ; 
    $n = count($exts)-1; 
    $exts = $exts[$n]; 
    return $exts; 
}

function validFilename($filename)
{
    $filename = str_replace(" ", "_", $filename);
    $pattern = "/[^[a-z0-9_-]/";
    return preg_replace($pattern, "", strtolower($filename));
} 

UPDATE 1
I'm recieving the file through $_FILES. This gives me the following data:

  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload

UPDATE 2
I just found something. I could use getimagesize which will return an array of 7 elements. One of these elements [2] is IMAGETYPE_XXX.

So I try using this code:

function getExts2($filename)
{
    list(,,$type) = getimagesize($filename);
    return $type;
}

But it only returns the number 2...

(I also tried using exif_imagetype, but it only get PHP Error: Call to undefined function.)


Solution

  • Check filename with regexp. Use info about mimetype. Save file on server with md5 name. Store real filename on db.