What is the best way to determine whether or not a file is an image in PHP?

前端 未结 12 487
有刺的猬
有刺的猬 2021-01-22 07:25

I have a sever which people can upload files to. The problem is that some of the filenames are mangled (dont have any extension) and so I cannot immediately determine file type.

12条回答
  •  温柔的废话
    2021-01-22 07:45

    You can try to load the image into PHP's GD library, and see if it works.

    $file = file_get_contents('file');
    $img = imagecreatefromstring($file);
    if($img === FALSE){
      // file is NOT an image
    }
    else{
      // file IS an image
    }
    

提交回复
热议问题