Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check manually for jpeg end of file marker ffd9 (?) in php to catch truncation errors

Tags:

php

jpeg

corrupt

basically trying to remove corrupt, prematurely ending jpeg files from a collection. i figured if the end of file marker was absent then that meant the image is truncated and therefore i would consider it invalid for my purposes. is this method of checking sound? if so any ideas of how i could implement this in php?

cheers


1 Answers

try this:

$jpgdata = file_get_contents('image.jpg');

if (substr($jpgdata,-2)!="\xFF\xD9") {
  echo 'Bad file';
}

This would load the entire JPG file into memory and can result into an error for big files.

Alternative:

$jpgdata = fopen('image.jpg', 'r'); // 'r' is for reading
fseek($jpgdata, -2, SEEK_END); // move to EOF -2
$eofdata = fread($jpgdata, 2);
fclose($jpgdata);

if ($eofdata!="\xFF\xD9") echo 'Bad file';
like image 59
Peter Avatar answered Oct 30 '25 23:10

Peter