How check file is image or not in php?

function isImage($image){
    $extension = pathinfo($image, PATHINFO_EXTENSION);
    $imgExtArr = ['jpg', 'jpeg', 'png'];
    if(in_array($extension, $imgExtArr)){
        return true;
    }
    return false;
}

This function will return true or false on the basis of the extension of files. It provides true if the file is an image or returns false if the file is not an image. You can pass more image file extensions to $imgExtArr variable.

Most of us would have come across the common solutions in PHP to check if the uploaded file is an image, you might have tried the usual way of checking the extensions and accepting the file to be a valid image, what if someone sinister uploaded a malicious script just by changing the extension of the file to .jpg or .gif ? . I bet most of us would have used the following to validate the image uploaded in PHP.

Check if uploaded image is valid with getimagesize( ) in PHP

$imagesizedata = getimagesize($file);
if ($imagesizedata ) {
//do something
}

but PHP docs says not to use getimagesize( ) to check that a given file is a valid image. it’s true that getimagesize( ) returns an array with some random values for image height & width, when the given file is not a valid image.

Check if uploaded image is valid by checking the extensions

$type=$_FILES[ 'image' ][ 'type' ];     
$extensions=array( 'image/jpeg', 'image/png', 'image/gif' );
if( in_array( $type, $extensions )){
//do something
}

but here you are checking only the extensions, like I said earlier, anyone can rename a file with a different content into jpg or gif and upload them without any problem.

Check if uploaded image is valid with exif data and fileinfo in PHP

Now let’s try something to check if the given image is valid, but before going into the example, let me tell you, even the following functions in PHP will not validate an image correctly.

  • finfo_file( )
  • mime_content_type( )
  • exif_imagetype( )

All the above functions will return the mime/image type for the given image, but they will fail as well if we upload a file after changing the extension or cheat with the first few bytes of image headers. Here is the example I was talking about. I have the following content in a file and saved it as motion.gif

GIF89a<

and used the following PHP code to check the validity of the image, you can see I have tried the four commonly recommended PHP functions to check if the given image is valid and each one of them failed.

";
echo $filename . ": "  . mime_content_type( $filename )  . "
"; echo "exif: " . exif_imagetype( $filename ) . "
"; print_r( getimagesize( $filename ) ); finfo_close( $finfo );

this is the output of the above code

How check file is image or not in php?
so all the above mentioned solutions to check if the uploaded files is a valid image will deceive us in the end, the only best solution is to use imagecreate function in PHP, we have separate functions for jpg, gif , png or to create image with the given string or content of the file. imagecreate function will return false when it fails to create an image with the given image file., so you can check if the given file is a valid jpg or gif or png.

here is the code I tried, to validate the uploaded image files.

You can experiment yourself with various images and cheating with the first few headers of jpg, gif or png.

how to check whether file is image or video type in php version 5.2.9

Nội dung chính

  • How to check if file is image in php?
  • How to check uploaded file is image or not?
  • How can I tell what type of video a file is?
  • How can I get URL from image or video in PHP?

asked Jun 19, 2010 at 5:59

1

$mime = mime_content_type($file);
if(strstr($mime, "video/")){
    // this code for video
}else if(strstr($mime, "image/")){
    // this code for image
}

Should work for most file extentions.

answered Jun 19, 2010 at 9:37

SemasSemas

85910 silver badges22 bronze badges

See my answer to

  • How can I check if a file is a mp3 or image file?

Example Code

 function getMimeType($filename)
 {
     $mimetype = false;
     if(function_exists('finfo_fopen')) {
         // open with FileInfo
     } elseif(function_exists('getimagesize')) {
         // open with GD
     } elseif(function_exists('exif_imagetype')) {
        // open with EXIF
     } elseif(function_exists('mime_content_type')) {
        $mimetype = mime_content_type($filename);
     }
     return $mimetype;
 }

2

You can check the MIME type using the finfo_file function

Example from the help page


EDIT: after better checking your question, this won't work, finfo functions require PHP 5.3.0

answered Jun 19, 2010 at 6:27

niconico

49.9k17 gold badges86 silver badges112 bronze badges

if(isset($_FILES['my_file'])) {
$mime = $_FILES['my_file']['type'];
if(strstr($mime, "video/")){
$filetype = "video";
}else if(strstr($mime, "image/")){
$filetype = "image";
}else if(strstr($mime, "audio/")){
$filetype = "audio";
}  

answered Jan 8, 2016 at 4:38

Randel FordbergRandel Fordberg

1051 gold badge2 silver badges11 bronze badges

2

I use the following code which IMO is more universal than in the first and the most upvoted answer:

$mimeType = mime_content_type($filename);
$fileType = explode('/', $mimeType)[0];

I hope it was helpful for anyone.

answered Jan 17, 2019 at 20:54

Paul BasenkoPaul Basenko

8651 gold badge9 silver badges22 bronze badges

Rather old question, but for others looking at this in the future, I would handle this like so:

function getType($file): string
{
    $mime_type = mime_content_type($file);

    return strtok($mime_type, '/');
}

This method utilises strtok to return the portion of the $mime_type string before the first /.

For example, let's say $file has a $mime_type of video/mp4, the getType method will return video.

answered Jan 23, 2021 at 11:45

Ben CareyBen Carey

16k19 gold badges83 silver badges160 bronze badges


Let’s say the following is our variable wherein we have an .mp4 path file −

$movieFileType="demo.mp4";

To check whether the above file is video type, use end() along with explode(). You need to set this in strtolower() and check the condition −

if(strtolower(end(explode(".",$movieFileType))) =="mp4") {
}
else {
}

Example






This will produce the following output −

Output

The movie demo.mp4 is of video type.

Updated on 12-Oct-2020 12:51:18

  • Related Questions & Answers
  • How to check if a file exists or not in Java?
  • PHP program to check if a number is prime or not
  • How to check if a file exists or not using Python?
  • Check whether the file is hidden or not in Java
  • PHP program to check if a year is leap year or not
  • Java Program to check whether a file exists or not
  • How to check if a file is a directory or a regular file in Python?
  • How to check whether a number is finite or not in JavaScript?
  • How to check whether a thread is alive or not in C#
  • How to check if a matrix is invertible or not in R?
  • How to check whether a NaN is a NaN or not in JavaScript?
  • PHP program to check if a given number is present in an infinite series or not
  • How to check if a file is readable, writable, or, executable in Java?
  • How to check whether a number is prime or not using Python?
  • How to Check Whether a String is Palindrome or Not using Python?

How to check if file is image in php?

The getimagesize function of php provides lot of information about an image file , including its type. The type can be used to check if the file is a valid image file or not. $a[0] and $a[1] are the width and height of the image. $a[2] has the image type.

How to check uploaded file is image or not?

Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType..

I tried ImageIO. ... .

ImageIO. ... .

Salih is right. ... .

@KyungMin: Non-images will indeed return null (and the toString() will then throw NPE)..

How can I tell what type of video a file is?

Which file format is my video file? On Mac, right-click the video file and click “Get Info”, then under “More Info” you should see both the video and audio codec. On Windows, right-click the file and click “Properties”. Under the “Details” tab you will see the file format and codecs used.

How can I get URL from image or video in PHP?

There are a few different approaches..

Sniff the content by looking for a magic number at the start of the file. ... .

Load the image using the GD library to see if it loads without error. ... .

If you really don't want to make an HTTP request for the image at all, then this rules out both sniffing and getting HTTP headers..

How do you check if a file is an image in PHP?

PHP check if file is an image.
1) Solution. The getimagesize() should be the most definite way of working out whether the file is an image: if(@is_array(getimagesize($mediapath))){ $image = true; } else { $image = false; } ... .
2) Solution. Native way to get the mimetype: ... .
3) Solution..

How can I tell if file is image or video PHP?

“php check if file is video” Code Answer.
$mime = mime_content_type($file);.
if(strstr($mime, "video/")){.
// this code for video..
}else if(strstr($mime, "image/")){.
// this code for image..

How do you check if an uploaded file is an image or not?

Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.

How check image is set or not in PHP?

php $filename = '/path/to/foo. txt'; if (file_exists($filename)) { echo "The file $filename exists"; } else { echo "The file $filename does not exist"; } ?>