Search code examples
phpfunctionfile-type

File type functions not supported on a live server in PHP


I have application on a live server where I want to check upload file is image or not. In my localhost and other live server following functions are working except one current server.

1. mime_content_type($file);
2. $file_type = exec("file $file");
3. $finfo = new finfo(FILEINFO_MIME);
   $file_type = $finfo->file($_FILES['image']['tmp_name']);

Some are deprecated, some are disabled due to security reasons. Can I have other methods/techniques to get file type which is used to check whether upload file is image or not?


Solution

  • You can use getimagesize() to determine if the uploaded file is image or not.

    Use it like this,

    $image_info = getimagesize($_FILES['file']['tmp_name']);
    if ($image_info === FALSE) {
       die("Uploaded file is not an image.");
    }
    

    getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondent HTTP content type.

    It will return FALSE in case of uploaded file is not an image.