Page 1 of 1

Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 1:15 pm
by jdmfontz
I am trying to restrict users from uploading specific file types into server. I realize that can use the following conditionals to restrict file types to those specified:

<?php

//Upload the file to server

$uploaddir = '/usr/local/apache2/htdocs/files/';
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "text/plain"))
&& ($_FILES["file"]["size"] < 20000))
{
. . .

I am having problems restricting files to only .csv file types which are really comma separated text files. Does anyone knows how to do that? I tried something like:

if ((($_FILES["file"]["type"] == "text/csv")

but that does not work. Any help is appreciated.

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 2:26 pm
by jazz090
mate, i do not recomend using mime_types, instead just create an array with allowed or dosalowed EXTENSIONS so say u just wanted images being uploaded:

Code: Select all

<?php
$exts = array("jpg", "jpeg", "bmp", "png", "tif", "gif");
$ext = pathinfo($_FILES['file'], PATHINFO_EXTENSION);
if (!in_array($ext)){
    //throw exception or error
}
?>

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 3:42 pm
by pickle
Actually, MIME types are much better than extensions. Any random user can easily change the extension on a file. It's much harder to change the MIME type.

Just upload a CSV & see what the file type is, then only allow that type.

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 3:58 pm
by jdmfontz
Thanks,

I was just going to say the same thing, it is easy to change file extensions.

Thank you again, it worked.

if (! empty ($userfile) && $filesize < 999999999 && $filetype == 'application/vnd.ms-excel') {
echo "<br />" . $filetype . "<br />";

Not certain why I did not think of this.

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 4:03 pm
by pickle
Hmmm, that raises an issue. If you make a csv file with Notepad or Textedit & upload it - it's not going to have that type of mime type, it will be what you originally tested for: text/csv. I'm not sure how to fix that, as it's possible it could be any number of MIME types.

Maybe trying fgetcsv() on the first line of the file would do it?

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 4:11 pm
by jazz090
yh u can change the extension of the file and php will still read it as its mime-type which is associated with the extension, u can chnage msword(.doc) file into .jpg, php will still read it image/jpg, i have tested this issue many times and there is NO DIFFERENCE between the two methods

Re: Restricting file types to .csv on upload

Posted: Mon Apr 20, 2009 4:17 pm
by jdmfontz
Wicked. Just changing any file extension to .csv makes the file application/vnd.ms-excel. Will use fgetcsv() instead.

Thank you,

m