Search code examples
phpgdcaptcha

PHP GD: The image cannot be displayed because it contains errors


I try to make Captcha via PHP GD. But unfortunately I encounter to a problem! PHP tell me:

The image “http://127.0.0.1/par.php” cannot be displayed because it contains errors.

My code is this

<?php

  header ('Content-Type: image/png');
  $im = @imagecreatetruecolor(120, 20)
        or die('Cannot Initialize new GD image stream');
  $text_color = imagecolorallocate($im, 233, 14, 91);
  $red = imagecolorallocate($im, 255, 0, 0); 
  for ($i=0;i<=120;$i=$i+1){
      for ($j=0;$j<=20;$j=$j+1){
          imagesetpixel($im, $i,$j,$red);
      }
  }
  imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
  imagepng($im);
  imagedestroy($im);
?>

Solution

  • $im = @imagecreatetruecolor(120, 20)
          or die('Cannot Initialize new GD image stream');
    

    You first hide the real error and TRY to display something...

    which you can't display because you don't look for it,

    and expose the image no matter if it really got generated.

    Then you go on stackoverflow and hope someone can guess the error you might have simply suppressed using @ operator.

    Make sure there is nothing before <?php and if you have, remove ?> at the end.

    To make sure you have GD installed try this in a new php file:

    <?php
    if (extension_loaded('gd') && function_exists('gd_info')) {
        echo "PHP GD library is installed on your web server";
    }
    else {
        echo "PHP GD library is NOT installed on your web server";
    }