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

╄→гoц情女王★ 提交于 2019-12-05 02:07:54

问题


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:


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';



回答2:


I solved this problem with a try catch and a @ in front of the function:

    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));
    }


来源:https://stackoverflow.com/questions/1459882/check-manually-for-jpeg-end-of-file-marker-ffd9-in-php-to-catch-truncation-e

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!