Handle error when getimagesize can't find a file

前端 未结 4 446
挽巷
挽巷 2021-02-05 06:53

when I\'m trying to getimagesize($img) and the image doesn\'t exist, I get an error. I don\'t want to first check whether the file exists, just handle the error.

4条回答
  •  野的像风
    2021-02-05 07:06

    Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:

    ob_start();
    $data = getimagesize('not-existing.png');
    $resize_warning = ob_get_clean();
    if(!empty($resize_warning)) {
      print "NOT OK";
      # We could even print out the warning here, just as PHP would do
      print "$resize_warning";
    } else {
      print "OK"
    }
    

    Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.

提交回复
热议问题