jhunlio
jhunlio

Reputation: 2660

input file type, upload only selected extension

I have php file to upload different kind of image file like .jpg, .gif an soon but my problem is that i also need to upload file like Microsoft office file like .doc, .docx, and .xlsx and I can't figure out how to make this thing work with that kind of extension, also video and music is restricted to upload.

my current code below:

function

function GetExtension($imagetype){
 if(empty($imagetype)) return false;
 switch($imagetype){
   case 'image/bmp': return '.bmp';
   case 'image/gif': return '.gif';
   case 'image/jpeg': return '.jpg';
   case 'image/png': return '.png';
 default: return false;
 }
}

code process

if(isset($_POST['submit'])){

    $tmp_file = $_FILES['file_upload']['tmp_name'];
    $target_file = basename($_FILES['file_upload']['name']);
    $imgtype = $_FILES['file_upload']['type'];
    $ext = GetImageExtension($imgtype);
    $imagename = date("d-m-Y")."-".time().$ext;
    $upload_dir = "../images/file/".$imagename;

    if(move_uploaded_file($tmp_file, $upload_dir)){

        //// some code here...........

    } else {
        $error = $_FILES['file_upload']['error'];
    }
}

Upvotes: 0

Views: 53

Answers (1)

Kausha Mehta
Kausha Mehta

Reputation: 2928

You can get the extension like below:

function GetExtension($imagetype){
 if(empty($imagetype)) return false;
 switch($imagetype){
   case '.bmp': return true;
   case '.gif': return true;
   case '.jpg': return true;
   case '.png': return true;
   case '.doc': return true;
   case '.docx': return true;
   case '.xls': return true;
   case '.xlsx': return true;
   default: return false;
 }
}


....
$path = $_FILES['file_upload']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$check_ext = GetImageExtension($ext);
if($check_ext) {
    ....
}
....

Upvotes: 1

Related Questions