-2

Possible Duplicate:
How can I only allow certain filetypes on upload in php?

i'm learning PHp and Mysql. I want to create a function that allow only specific file extension which uploaded by user. Like..

$whitelist = array("jpg","jpeg","gif","png","bmp","pdf" );

So how do i check this specific file extension with php. Can anyone tell me please.. Thank you.

Community
  • 1
  • 1

3 Answers3

2

This is an option:

function checkFormat($source){
    $whitelist = array("jpg","jpeg","gif","png","bmp","pdf" );
    $type="";
    if(version_compare('4.3.0', PHP_VERSION) > 0){
        $type=mime_content_type($source['tmp_name']);
    }else{
        $type=$source['type'];
    }

    return (in_array($type, $whitelist));
}

Regards!

Lobo
  • 4,001
  • 8
  • 37
  • 67
2

Get the file extension of the uploaded file with pathinfo­Docs like

$extension = pathinfo($filename, PATHINFO_EXTENSION);

and then check against a whitelist of allowed exentsions

$allowedExtensions = array("jpg","jpeg","gif","png","bmp","pdf");
$isAllowed = in_array($extension, $allowedExtensions);

maybe you need to modify the extension recognize function to get some special extensions like tar.gz, but that should do the trick.

Edit: As said here you shouldn't check the file extension, but the mime-type.

Community
  • 1
  • 1
Stefan
  • 2,028
  • 2
  • 36
  • 53
0

Look here: http://www.w3schools.com/php/php_file_upload.asp

It provides an example that shows how to do it.

yoni0505
  • 349
  • 2
  • 4
  • 8