File upload limitation by file type and size.

I have this piece of PHP code here and I need it to limit the uploadable file type to .csv and size to 2 mb.
It does have file size limit but it does it in the weird way and it doesn’t limit the file extension.
What to do?

[php]<?php
$connect = mysql_connect(“localhost”,“root”,“asdasd”);
mysql_select_db(“nooruse”,$connect) or die (‘Viga andmebaasi valimisel’);

if ($_FILES[csv][size] > 0) {

$file = $_FILES[csv][tmp_name]; 
$handle = fopen($file,"r"); 
 
do { 
    if ($data[0]) { 
        mysql_query("INSERT INTO norse5_proov (osakond, soetusaasta, it_number, tooteruhm, mudeli_nimetus, sn, riigivara_nr, inventaari_nr, maja, ruum, vastutaja, markus, kasutajanimi) VALUES 
            ( 
                '".addslashes($data[0])."', 
                '".addslashes($data[1])."',
				'".addslashes($data[2])."',
				'".addslashes($data[3])."',
				'".addslashes($data[4])."',
				'".addslashes($data[5])."',
				'".addslashes($data[6])."',
				'".addslashes($data[7])."',
				'".addslashes($data[8])."',
				'".addslashes($data[9])."',
				'".addslashes($data[10])."',
				'".addslashes($data[11])."',
                '".addslashes($data[12])."'
            ) 
        ") or die(mysql_error()); 
    } 
} while ($data = fgetcsv($handle,1000,",","'")); 

header('Location:insert.php?success=1'); die; 

}

?> [/php]

I am by no means an expert on this matter and hopefully some of the other members can contribute, but this is something i have also been looking into to suit my needs.

With regards to file size, from what i can see you already have the code in place but you haven’t set a file size.
Something like this should do

if ($_FILES['csv']['size']>2097152) { die('file size is restricted to 2MB'); }

With regards to restricting file type, there are several MIME types for CSV depending on OS & browser. Here is one way of validating MIME types.

[code]$csv_mimetypes = array(
‘text/csv’,
‘text/plain’,
‘application/csv’,
‘text/comma-separated-values’,
‘application/excel’,
‘application/vnd.ms-excel’,
‘application/vnd.msexcel’,
‘text/anytext’,
‘application/octet-stream’,
‘application/txt’,
);

if (in_array($_FILES[‘upload’][‘type’], $csv_mimetypes)) {
// possibly a CSV file
}[/code]

I’m sure there are other, better ways to do it … but just thought i’d throw in my 2 cents worth and maybe i can learn from this also.

Thank you for this piece of code but I have no idea how to use it in my code. Could you please show me?

Sponsor our Newsletter | Privacy Policy | Terms of Service