Usando php para verificar el tipo de archivo MIME cargado a través del formulario

Ok, so I'm creating a website that will let users upload csv-files that are to be scanned in to a mySQL-databse. Because I don't want to risk evil people uploading strange files that can mess with my database I'm guessing it's a good idea to check the mime type of the file. From other threads I've understood that the only way to properly do this is by using finfo(). But I don't get it to work. The following code in my uploadfile.php just prints out the temporary file name followed by "hello".

$filename = $_FILES["file"]["temp_name"];
echo $filename;

if (function_exists('finfo_open')&&$mode==0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); 
echo finfo_file($finfo,$filename);
finfo_close($finfo); 
echo "hello";
}

So I know that the file has uploaded correctly, I know the function exists, I know that there is no error throughout the if clause. So then why won't it work? I'm testing this through MAMP, and am thinking that maybe there is some error there? Though it has PHP Version 5.4.4.

I have also tried different versions like:

$mimetype = finfo_file($finfo,$filename); 
echo $mimetype;

But nothing works. It never prints any mime type :( What can I do to fix this?

preguntado el 12 de junio de 14 a las 10:06

1 Respuestas

finfo_file can and will return empty string and FALSE if the type is not found.

Problem with mime types here is, you can't trust them either.

I did this before and parsed the files with fgetcsv. Any error there and I discarded the file. This way you can be sure it was valid csv.

When you insert into your database make sure you do the proper escaping or use prepared statements.

Respondido el 12 de junio de 14 a las 10:06

Hallelujah! Now I don't feel so alone in the universe anymore :) From your suggestion I created the code: $filename = $_FILES["file"]["tmp_name"]; $file = fopen($filename,"r"); print_r(fgetcsv($file)); fclose($file); And it prints the first line of the file. So if fgetcsv returns false then I'll stop the file then? - emilyaro

If it returns FALSE there is definitly something wrong with that file and you should discard it. If you get a valid response, you should do some further checking. For example if it found too few or too many fields. If each line has the same amount of fields, and so on. - colburton

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.