Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

mysql - php file upload, how to restrict file upload type

I have the following code to check if (resume and reference letter uploaded match desired type (pdf OR doc OR docx) and size (less than 400 kb)

//check file extension and size
         $resume= ($_FILES['resume']['name']); 
         $reference= ($_FILES['reference']['name']); 
         $ext = strrchr($resume, ".");
         $ext1 = strrchr($reference, ".");
        if (!(($_FILES["resume"]["type"] == "application/doc")
        || ($_FILES["resume"]["type"] == "application/docx")
        || ($_FILES["resume"]["type"] == "application/pdf" ))
         && (($_FILES["reference"]["type"] == "application/doc")
        || ($_FILES["reference"]["type"] == "application/docx")
        || ($_FILES["reference"]["type"] == "application/pdf"))
        && (($ext == ".pdf") || ($ext == ".doc") || ($ext == ".docx"))
        && (($ext1 == ".pdf") || ($ext1 == ".doc") || ($ext1 == ".docx"))
        &&  ($_FILES["resume"]["size"] < 400000) //accept upto 500 kb
        &&  ($_FILES["reference"]["size"] < 400000)) {  

stop user } else { allow files to upload }

This is not working as desired, allows even txt files through + the size limit is not being checked, what is wrong with it?

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The below just uses the mime types to validate a file, then checks the size of both. For a list of most mime types see here or google.

function allowed_file(){

//Add the allowed mime-type files to an 'allowed' array 
 $allowed = array('application/doc', 'application/pdf', 'another/type');

//Check uploaded file type is in the above array (therefore valid)  
    if(in_array($_FILES['resume']['type'], $allowed) AND in_array($_FILES['reference']['type'], $allowed)){

   //If filetypes allowed types are found, continue to check filesize:

  if($_FILES["resume"]["size"] < 400000 AND $_FILES["reference"]["size"] < 400000 ){

    //if both files are below given size limit, allow upload
    //Begin filemove here....

    }

    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...