Manually check for jpeg the end of the file marker ffd9 (?) In php to catch truncation errors

basically trying to remove corrupt, prematurely ending jpeg files from the collection. I realized that if the end-of-file marker was missing, this means that the image is truncated, and therefore I consider it invalid for my purposes. Is this a sound verification method? if so, what ideas can i implement in php?

amuses

+3
source share
2 answers

try the following:

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

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

This will load the entire jpg file into memory and may result in an error for large 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';
+4
source

try catch @ :

    try
    {
        if (!@imagecreatefromjpeg($photoPath)
            throw new Exception('The image is corrupted!');
    }
    catch(Exception $e)
    {
        $error = $e->getMessage();
        Yii::app()->user->setFlash('addphoto', Yii::t('app', $error));
    }
0

Source: https://habr.com/ru/post/1718279/


All Articles