Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

php - Catch exception from imagecreatefromstring()

I have the following code that contains two B64 image strings (truncated for readability) in an HTML file on my server (I'm using PHP7.0.33 on Debian Stretch). I'm simulating a transmission error by changing a letter in the string. If I change any of the first 33 characters imagecreatefromstring() just terminates the program without being caught by the catch block, or showing any error as shown in the output.

Anyone know what I can do to catch this error?

Thanks Derek

Program output is...

Start

Process...Good

image/jpeg

OK here

false...Good

Finish Image...Good

.......................

Process...Bad

image/jpeg

OK here

<?php


echo "Start<br><br><br>";

$Good ="/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBA...

$Bad  ="/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDBAIBAQIBA

                                         <----CHANGE A to B  
 

try
    {
    echo "Process...Good<br>";
    $D2=base64_decode($Good,true);
    $f = finfo_open();
    echo finfo_buffer($f, $D2, FILEINFO_MIME_TYPE); 
    finfo_close($f);
    echo"<br>OK here";
    if (@imagecreatefromstring($D2)===false)
        {
        echo "<br>true...Good";
        }
    else 
        {
        echo "<br>false...Good";
        }
    echo"<br>Finish Image...Good";
    }
catch(Throwable $e)
    {
    echo "<br>In Catch Error...Good";
    }


echo"<br>.......................<br>";


try
    {
    echo "Process...Bad<br>";
    $D2=base64_decode($Bad,true);
    $f = finfo_open();
    echo finfo_buffer($f, $D2, FILEINFO_MIME_TYPE);     
    finfo_close($f);
    echo"<br>OK here";
    if (@imagecreatefromstring($D2)===false)
        {
        echo "<br>true...Bad";
        }
    else 
        {
        echo "<br>false...Bad";
        }
    echo"<br>Finish Image...Bad";
    }
catch(Throwable $e)
    {
    echo "<br>In Catch Error...Bad";
    }

echo "<br><br><br>Finish";


?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks to all for viewing.

As CBroe says, imagecreatefromstring() does not throw exceptions.

I found somewhere to add these lines to the code

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

and now I get the following error...

Fatal error: imagecreatefromstring(): gd-jpeg: JPEG library reports unrecoverable error: Bogus DQT index 4 in...

So the program bombs out without warning


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...