2

How to check image corrupt or not using url in php.Is it possible to check in php? I need to check using image url check image corrupt or not.

4 Answers4

6

Use getimagesize() it will return FALSE if file corrupt otherwise if file is ok then it will return array containing file info like mime, height and width etc, try below example

<?php
  $fileName = 'image/corruptsample.jpg'; //filepath
  if(getimagesize($fileName) === false){
    echo "file is corrupted";
  }
  else{
    echo "file is ok";
  }
lazyCoder
  • 2,544
  • 3
  • 22
  • 41
  • 4
    Only using getimagesize will only detect a subset of curruption types. Most of the common cases of corruption will **not** be detected. – Toto Oct 14 '18 at 01:15
2

If instead you are looking for a PHP solution instead of a javascript solution (which the potential duplicates do not provide), you can use GD's getimagesize() in PHP and see what it returns. It will return false and throw an error when the provided image format is not valid.

Otherwise You can try that way and get corrupted image

<?php
  $ext = strtolower(pathinfo($image_file, PATHINFO_EXTENSION));
  if ($ext === 'jpg') {
    $ext = 'jpeg';
  }
  $function = 'imagecreatefrom' . $ext;
  if (function_exists($function) && @$function($image_file) === FALSE) {
    echo 'bad img file: ' . $image_file . ' ' . $function;
  }
Nims Patel
  • 1,048
  • 9
  • 19
1

Try the following solution, which uses curl to retrieve the image from a URL and then validates it:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $img_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$img_data = curl_exec($ch);
curl_close($ch);

$img = @imagecreatefromjpeg($img_data);

if (!$img) {
    echo  "Invalid Image";
} else {
    echo  "Valid Image";
}
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
0
$external_link = ‘http://www.example.com/example.jpg’;
if (@getimagesize($external_link)) {
echo  “image exists “;
} else {
echo  “image does not exist “;
}

for more details Check whether image exists on remote URL

Umar Majeed
  • 313
  • 3
  • 15