imagecreatefrompng (and imagecreatefromstring) causes to unrecoverable fatal error

南笙酒味 提交于 2019-12-05 10:35:20

A bit late to the party, but i ran into this problem as well, and cannot wait for the bug fix to be included in my ubuntu LTS The only clean workaround i found is actually to use Imagick::valid() check the image is valid.

function imageIsValid($path)
{
    try
    {
        $imagick = new \Imagick($path);

        return $imagick->valid();
    }
    catch (\Exception $e)
    {
        return false;
    }
}

Of course, your server/hosting needs to have php imagick extension installed...

It seems to be fresh bug (and possibly not closed): https://bugs.php.net/bug.php?id=73986

So until I will find better way, I think it is only one way to check image. It is BAD code and i know it, but I have no other ideas. The idea is to try create an image in another thread and return check value depends on it's output.

$fname = tempnam('/tmp', 'test_');
$handle = fopen($fname, 'w');
fwrite($handle, $result);
fclose($handle);

$output = `php -r "imagecreatefrompng('$fname');" 2>&1`;
unlink($fname);

if (!empty($output)) {
    return null; // error
}
// good image

Backtrick operator will execute command in shell. Than it will output error to stderr. 2>&1 used to make stderr stream output to stdout stream so it can be accessed via backtrick operator.

Since PHP7 all errors are exceptions so you can simply wrap fragile code part inside try-catch block to catch the \Throwable exception and handle accordingly.

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