CAPTCHA image cannot be displayed because it contains errors

Tocacar
Tocacar used Ask the Experts™
on
I am working my way through a tutorial book ((Practical Web 2.0 Applications with PHP) and cannot get the CAPTCHA image to appear. The page returns as a "captcha (PNG Image)" that states:

      "The image "...URL here..." cannot be displayed, because it contains errors."

I have GD2 installed and enabled.  The code to generate the captcha is attached (the font path in $opt is retrieved from a settings.ini file and is:

paths.data  = "C:/Sites/phpweb20/data"

In that directory (data) there is a TrueType font file called VeraBd.

Can anyone see what I'm doing wrong? Any help/ advice would be most appreciated.
<?php
    class UtilityController extends CustomControllerAction
    {
        public function captchaAction()
        {
            $session = new Zend_Session_Namespace('captcha');

            // check for existing phrase in session
            $phrase = null;
            if (isset($session->phrase) && strlen($session->phrase) > 0)
                $phrase = $session->phrase;

            $captcha = Text_CAPTCHA::factory('Image');

            $opts = array('font_size' => 20,
                          'font_path' => Zend_Registry::get('config')->paths->data,
                          'font_file' => 'VeraBd.ttf');
			
			
            $captcha->init(120, 60, $phrase, $opts);

            // write the phrase to session
            $session->phrase = $captcha->getPhrase();

            // disable auto-rendering since we're outputting an image
            $this->_helper->viewRenderer->setNoRender();

            header('Content-type: image/png');
            echo $captcha->getCAPTCHAAsPng();
        }
    }
?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mark BradyPrincipal Data Engineer

Commented:
My guess is that the image that the script is trying to display is in CMYK format instead of RGB. CMYK formatted images are meant for printing not the screen. RGB is the only safe way to go for web images. Try opening that file up in photoshop and see if I am correct.

Author

Commented:
Unfortunately I haven't got Photoshop; is there another way I can check?

I've read other questions related to CAPTCHA images in the knowlegebase and one expert requested an author to post the results of print_r($opts) placed before $captcha->init.   The author seemed to solve their problem before doing this (they had a typo in the font filename) so this line of investigation didn't progress.  When I tried it, I got this:

Deprecated: Assigning the return value of new by reference is deprecated in C:\Program Files\PHP\PEAR\Text\CAPTCHA.php on line 169 Strict Standards: Non-static method Text_CAPTCHA::factory() should not be called statically, assuming $this from incompatible context in C:\Sites\phpweb20\include\Controllers\UtilityController.php on line 13 Array ( [font_size] => 20 [font_path] => C:/Sites/phpweb20/data [font_file] => VeraBd.ttf )

Do you think this is the problem/ know how I can fix it?

Thanks for your help.
Mark BradyPrincipal Data Engineer

Commented:
It may very well be the problem and could be the font as well. Let's rule out the image first. Get the image in question and post it here (add it as a file). I will check it's porperties so we can rule that out.
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Author

Commented:
I'm probably being a bit thick here but could you explain what you mean by 'Get the image in question...'?  I don't have an image.  According the book I'm following, the above code is supposed to generate a small image showing some distorted text using the VeraBd font.  I can't get it to show in the browser; I just get the text displayed saying that the image couldn't be displayed because there were errors.

Sorry, I'm a total beginner with this.  Please tell me what you mean (and thanks for helping me, I appreciate it!).

Author

Commented:
OK, I think I know what you mean.  I saved the browser page as a file (png ¦ see attached as 'captcha.png'), but it won't open in anything due to "corruption" (which is why I guess it doesn't show in the browser also?).  I did manage to open it in Notepad++ and saw a list of errors before the png image was meant to start:



I've done some more research and found at least two other people with exactly the same problem (one on the PEAR forum, the other on the Zend Framework forum).  Both ended with the same solution; they had an empty line at the top of their bootstap (index.php) file.  Unfortunately, I don't (see various relevant code files attached).
Deprecated: Assigning the return value of new by reference is deprecated in C:\Program Files\PHP\PEAR\Text\CAPTCHA.php on line 169

Strict Standards: Non-static method Text_CAPTCHA::factory() should not be called statically, assuming $this from incompatible context in C:\Sites\phpweb20\include\Controllers\UtilityController.php on line 13

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in C:\Program Files\PHP\PEAR\Text\CAPTCHA\Driver\Image.php on line 215

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in C:\Program Files\PHP\PEAR\Image\Text.php on line 479

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in C:\Program Files\PHP\PEAR\Image\Text.php on line 667

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in C:\Program Files\PHP\PEAR\Image\Text.php on line 921

Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in C:\Program Files\PHP\PEAR\Text\CAPTCHA\Driver\Image.php on line 299
‰PNG

Open in new window

index.php
CustomControllerAction.php
UtilityController.php
captcha.png
Mark BradyPrincipal Data Engineer

Commented:
I have requested attention from the moderators on this one as I am out of ideas. Sorry i can't be of more help.
Top Expert 2005

Commented:
I am working my way through a tutorial book ((Practical Web 2.0 Applications with PHP) and cannot get the CAPTCHA....

1. You could check the publisher's website as most now post "errata" or corrections to published books in that manner.

2. I understand you are learning and possibly getting past this hurdle is important on its own level, however, if you are building a public facing website you want to use reCAPTCHA: http://recaptcha.net/.

It is free and it solves many problems that plague most CAPTCHA implementations including the most difficult...accessibility.

Regards,
Rod

Author

Commented:
@Rod

Thanks for your advice.  I've already checked the publisher's errata site, but there is no mention of this problem.  I'd really like to solve it for the learning value but, as you say, I may need to skip it for now to continue with the book.  I'd rather not let it go by unsolved though....  Do you know what I should try to get it to work?  Any suggestions most appreciated.

I'll have a look at recaptcha too for future projects, thanks for suggesting this.  

Author

Commented:
@elvin66

Thanks very much for your help, and for requesting extra attention from the moderators.  I still hope to find a solution...
Most Valuable Expert 2011
Top Expert 2016

Commented:
I agree with Rod about ReCaptcha.  Here is the captcha code that I have used successfully in the past (three pieces to the puzzle).  Best, ~Ray
<?php // captcha_number.php GENERATES A PICTURE OF A NUMBER INTO THE BROWSER OUTPUT
error_reporting(E_ALL ^ E_NOTICE);

// DECODE THE INCOMING STRING
$data = base64_decode($_GET['dt']);

// CREATE AN IMAGE RESOURCE - CHOOSE THE SIZE THAT BEST MATCHES YOUR PAGE STYLE
$im   = imagecreate(46,13);

// WHITE BACKGROUND
$bg   = imagecolorallocate($im, 255,255,255);

// GRAY STRIPES
$gray = imagecolorallocate($im, 188,188,188);

// FIREBRICK TEXT
$text = imagecolorallocate($im, 178,34,34);

// ADD THE NUMBER TO THE IMAGE
imagestring($im,5,4,0,$data,$text);

// WRITE A GRAY STRIPE (OR MORE IF YOU CHOOSE)
imageline($im,4,12,38,0,$gray);

// SEND THE IMAGE INTO THE BROWSER OUTPUT STREAM
imagepng($im);
imagedestroy($im);
?>







<!-- THIS HTML GOES IN THE FORM SCRIPT - STYLE IT TO SUIT YOUR PAGE STYLE -->
Type <img style="display:inline;" src="captcha_number.php?dt=<?php $x = mt_rand(1000,10000); echo base64_encode($x); ?>" /> here:
<input name="_newCode" type="text"   maxlength="64" size="6" autocomplete="off" />
<input name="_newMd5"  type="hidden" value="<?php echo md5($x); ?>" />







<?php // THIS SEGMENT GOES IN THE ACTION SCRIPT TO VALIDATE THE FORM INPUT
if ($_POST["_newMd5"] != md5($_POST["_newCode"])
{
    // MIGHT WANT TO MAKE THIS USER-FRIENDLY
	die('Security code number did not match');
}

Open in new window

greetings Tocacar, , I believe the" Strict Standards" warning messages you are getting are PHP warning messages that are set in the php.ini for the kinds and types of error messages that are displayed for PHP, I do not have the E_STRICT set in my php.ini, so I do not have direct experience with that. However I have use the -
ini_set("display_errors", 0);
to turn off error and warning messages from PHP
perhaps if you add it in the -

if (isset($session->phrase) && strlen($session->phrase) > 0)
                $phrase = $session->phrase;
            ini_set("display_errors", 0);
            $captcha = Text_CAPTCHA::factory('Image');

it might get your CAPTCHA to make a valid png image?

Author

Commented:
@Slick812
Thanks very much for your suggestion.  I tried using ini_set(), but that had no effect.  

@Ray_Paseur
Thanks for posting your code.  I'm a total newbie, so I can't quite get my head around it yet...BUT!...after inserting several var_dump()'s throughout the captchaAction function in the UtilityController file, in an attempt to find out where the problem occurs, I discovered that it is this line causing the problem:

header('Content-type: image/png');

Without this, I get a scamble of characters on the page, which I now know is the raw png image data.  So, I know that the captcha stuff is working, it's just this header() line getting in the way that's causing the "corruption" in the image.

This is my first attempt at trying to put together a site using OOP, so my head isn't 100% fully around it yet.  I think I'm about 95% of the way there, I just need it all to 'click'.  Understanding and solving this problem is going to help my understanding, so I really want to get to the bottom of it.  

I know that you can't pass a header if there has already been output.  For the timebeing, I'm calling the image page directly (http://..siteurl../utility/captcha)  This just calls the 'captchaAction' function in the UtilityController file, which is in my Controllers directory. There is no other output here, just the image, so I don't understand why the header() line causes a problem here.  

I obviously want to display this captcha image (eventually) in a <div> on a registration page (among others), which will have output displayed before the captcha page is called as an image tag, so I can see how the header() line might cause problems there...., but getting the image to just show on it's own is the first challenge.

I would be hugely greatful to anyone who can advise me on what to do next...  THANKS!


Author

Commented:
When I remove the header() line, the raw png data I get looks like this when I view the source (see below).  There is a couple of inches of white space in Line 1 (approx 3 tabs), before "‰PNG".  Do you think it is this space that is causing the error (i.e., could this be the "output" before the header?).  I have no idea where this empty space is coming from and don't know whether or not it is significant.



‰PNG

¿¿¿
IHDR¿¿¿x¿¿¿<¿¿¿"Ïéÿ¿¿°IDATxœí\ÍkÏ×—¬:6QZ	J$B	Mk¥iÚÞJ ´ÿA¡´Ð›ArÈ!‡ðÚSÿ‚Òs_ IK¡©©Bz¨i¦bŒ±qÕøþ=Ì/ÃdW×uwÕMó{NîììÌgžyö³ÏìN¢zðàø?zjÐœœ¢ý~¿ßïlšÁvßk ~ƒÁà 9ûDûý~.X¿J A¢[Ž¶×h©ÖK¸ÝÄË@ô XV Å-@¡žÉÔA²¬,ÑQmR‰î³œIÕ\ÂܐZžE§Î’¢QÐØ«
œbЍÎTRV†ý”³BR†É&ù9ŠVÅ@”ÂÄÝ9+“b ,?"‰î5Ë
¤´µö••:Xo$”Ã2GnWÎ*Ct/äÌòmÊ¡´_n¤0xE³D¡(–¹‚íÖl`tM´\DpE¡wŒ ïúS6EO¯í^õˆâl6›N§Ëå2MÓ£££ÃÃÃ/‘²þl7îˆæy'Ùñ(¤³Ül6³Ù,s‚Z­6;;[­V¿~ýúçÏ\-‹9Ž™™¦õÀqز¯?{õ®ƒ|¬ñD,×`F("KjµÚçÏŸ3™«æïß¿‹Å¢×ëU«ÕÜ`0ÅâBâ¹°¢[>|;ÄSGàxjµZ¹\®×ëZ­V¯×·¬£V«
C±XÄ%±X,“Éèt:‹ÅR(òù<>•Éd677¯\¹BFÒUH" ”è®Xfe‰v	f2™L&S¯×].*)‹Éd2N–J%|MÓ‡cjjjhhˆÕ „$úׯ_6›Íãñ ånnnþøñŸÇãN§5"×]Å?I2Û;ž q}ñâ¿`qqqvv¶T*}ùòåàà¿¿ Õj].×îîîÖÖ÷–G8>>þùóg2™œŸŸ§iš<!L§ÓdÉÕ«Wq~p¹\{{{¹\nllàjýñ9‚ˆî(g~÷ƒßÚÚZ(
‡Ãn·•W*•OŸ>¡ÃjµZ.—c±)Ì–(
‘HäæÍ›d!„uÈÊ3ãããß¿¿„Ãa20þ¾¢/þÁ	¿üF*Ì2¿ QeµZu:]&“ae¿¡Íf³Z­ÃÃÃz½¾V«%‰H$Òh4еÉd2ŸÏ›L&Ü‹h®¯xùò%yxçΝ۷o#®û êÎD³â@¿œPŒ2€#?~üH¶¼³³c0¼^/â«ÙlÖj5»Ýît:GGGÉšZ­vbb"—Ëmmmá½½=§Ó‰YDW*r¿€ÕÕÕ7oÞà[Ê`0t»@™ª®½´´„~`mv4R@¿•pÓèôô4V¥J¥Òjµ“““ÜN…Ã0Õj•,DóÁ"ºX,²ÚÊÊÊÊÊ
® Õj;VFt š»
ƒoß¾]__ÇuxŒÔ»wï¿‘
Y\Pe³ÙÚuÍf‰Äþþ~.—ÃNîjµš¦éããcp’…Ÿ>}:>>Žƒ_ZZBa#Q£	–ž7¶ÀG4¹Ü¿ÄƒBèv»ñ=ØÎH¡
Emll kYDÓ4­R©¸ý
…oß¾±´ß²* žÉ(0¡Ýn_^^FÁÇãq|–|ò÷"ºP4†#õáÃ4ZRŒ,¢ëõ:·Çjµº¾¾Î24M›L&£Ñ¸»»‹¯ª×ë¥RI¯×c~>|øúõkœÓ†Y^^~üø1EQ‰D"•JáçççïÞ½KQR·
¿!:,ù[žE|aQ³ŒZÂâцÃáû÷ï{<À!­÷XKáíím’e³Ù|ýúul`R©9=8çâ;G…4;77W.—ÙcÖh<t–»»3!+}Ìi¤Ðµøé‡ÆŒ³6J£dSä폀×N§³|pp€R0j9?yòœÎid¿÷îÝ[XX¸xñ"Ù Åbñù|f³™g€ÑU~g+ZÈ7R˜X;¤!5¨éštZBL¿€a˜.œ
è´ÿÝÙÙ1›Íjµ:NG£Qœ[QËSSS¬ÀÈ~†1>Ÿïðð0—ËQ522"ä5i/ fÁÂÊ¿ˆë–#ÒHAI#È0«ñK—.mooãÃT*õþý{pb$=zFÉËÉ	~þü9Ùu±Xl6›*•Êl6Ë"aÝÚ•Dwl‚4R¿€p8L)¿Àþþ>YŸgýÆ%zll,“QìñxnݺEò¥Ñhi!­ÑÜÜ®Ðh4
…«ÇAAäg¿ü<´ÛíX¹ØH!f™$´ÊÑ*•ÊëõÆb±W¯^¡·ÛmµZ}>ŸÅb©T*×®]ƒ’O`RBòé‡ÖôâÆÈ6ÐlBˆ#8†B¡ÉÉI®‘‚Ž‘‡d;\E¿ó][[ËçóÍfsqqO¡N§›˜˜ £§Ý„½äi 8E´ð‰"í*¿Àjµþýû7‰°[ç)¡ÃဍF$L²wôÅ V«GFFxbhçñÉÃ^-n1)r_dzgÏÈŠ¢Âá0ù ³X,333,²4͍7¸
‚.?€¶«Ï"š›š¶母GÈŽ#%î>œf³ùòåËøŽ1Â[–Þ;D~3ä¾*ëÊH‰ûz$ä*“É4==ÝU³ýÁÿˆî8Q¬
Z­vhh?ß))ÛP”°ƒIJ‚^üƒVÔte¤¤|¿UÚ&qп±;„)‰;©E±Ä[JxG"ðà-#%ä
!þãlK#%}3 P˜¤Ïºx¢YFjuuô~ÊÙ…x¢‘‘’EÂ
2‚,s/鏅€|¼ü«BƳý‘b[“r) »•!›‘^ÈB, ËÞ¦ìQöu€Þpq~„Œ!f»œ	!#È«†ÖD÷ˆˆs(dŒ>ýá2‚ìšèÑçYÈ’þ_Ç¿Š^(ã\üƒA%à?Úms)Ž{u¿¿¿¿IEND®B`‚

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
When you say the header "causes a problem" - what does that mean?

Author

Commented:
When the header() line is in there, I get:

 "The image "...URL here..." cannot be displayed, because it contains errors."

When I take it out, I get the raw png data (see code snippet in my latest post, viewed as source).
Most Valuable Expert 2011
Top Expert 2016

Commented:
Sidebar note - if you copy and paste information from the EE code snippet, you will have trouble with header() commands, and maybe others.  EE has been notified about the issue.  Their code snippet production is adding whitespace to the front of whatever it puts on the screen.  Seems to have started recently but it affects older posts as well as current ones.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Can you post the PNG as an attached file, please?

Author

Commented:
Re; your sidebar note, I'm getting that white space appear in my View Source window as well, so it isn't being generated by EE's code snippet function on this occasion.

Author

Commented:
Sorry for the short delay - see latest captcha page (saved from browser window as png) attached.  I've been messing around with it all day, and the various PHP warning messages have returned (don't know why yet, still fiddling with it hence the delay in posting) but the png raw data is still there (the 'header()' line is not present in the PHP script when this page is generated).
captcha3.png

Author

Commented:
Aha, the PHP warnings came back because I took out the "ini_set("display_errors", 0);" that Slick812 suggested above.  I've put that back in and now just see the raw png data - see this file (saved from the browser window) attached.
captcha4.png

Author

Commented:
In case you want it, I have also attached, as a png, the actual png image page that the browser displays when the header() line is included in the PHP script.  

By the way, thanks very much for your help with this.
captcha5.png
Most Valuable Expert 2011
Top Expert 2016

Commented:
PHP has various levels of errors, warnings and notices.  Notices are often the cause of unwanted browser output since they can arise from such relatively benign things as testing for equality of an undefined variable.  This might be helpful to turn off the notices.

error_reporting(E_ALL ^ E_NOTICE);
Most Valuable Expert 2011
Top Expert 2016

Commented:
OK, none of those files appear to be valid PNG file types.  I could not open any of them in an image editor.

Author

Commented:
I just turned off the error_reporting, as you suggested, but no improvement.

I know what you mean about the png files, I've been trying the same thing myself with no luck.  I cannot understand what the problem is..  It's so frustrating!

Going back to the code sample you originally posted...  Maybe if I can get that working, I can figure out how to make this one work(?).  Can you describe clearly what I need to do to achieve this please.  Do I need to separate it out into 3 separate files?  Do they all go in the same directory, etc.  I'm sure it seems obvious, but I can't quite figure it all out for myself (yet).

Thanks again for your help.
Most Valuable Expert 2011
Top Expert 2016

Commented:
May be worth reading the user-contributed comments here:
http://php.net/manual/en/function.header.php
http://www.php.net/manual/en/function.header.php#95058

Also, please install this script on your server and run it.  Let me know what comes out, thanks.
<?php // RAY_temp_tocacar.php
error_reporting(E_ALL);

// THE DATA STRING
$data = '1234';
if (isset($_GET["dt"])) $data = substr(trim($_GET["dt"]),0,5);

// CREATE AN IMAGE RESOURCE - CHOOSE THE SIZE THAT BEST MATCHES YOUR PAGE STYLE
$im   = imagecreate(46,13);

// WHITE BACKGROUND
$bg   = imagecolorallocate($im, 255,255,255);

// GRAY STRIPES
$gray = imagecolorallocate($im, 188,188,188);

// FIREBRICK TEXT
$text = imagecolorallocate($im, 178,34,34);

// ADD THE NUMBER TO THE IMAGE
imagestring($im,5,4,0,$data,$text);

// WRITE A GRAY STRIPE (OR MORE IF YOU CHOOSE)
imageline($im,4,12,38,0,$gray);

// SEND THE IMAGE INTO THE BROWSER OUTPUT STREAM
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

Open in new window

Most Valuable Expert 2011
Top Expert 2016
Commented:
Here is the captcha example code without the friggin' parse error that I accidentally put into my code sample when I was trying to make it pretty.

This is a three-part example.  Take the top part and install it in your web directory so you can call it like any script or HTML page.  It needs to be in the same directory as the HTML that calls it.  Name it "captcha_number.php" so the HTML can find it.

The second part is an HTML excerpt that needs to be added to your form.  It calls the captcha number script and gives it the number to be displayed.  It also passes the md5() code of the number to the action script (the one that processes the HTML form).

The third part of the example is the code that goes into the action script to test the client input for validity.

Hope that helps, ~Ray
<?php // captcha_number.php GENERATES A PICTURE OF A NUMBER INTO THE BROWSER OUTPUT
error_reporting(E_ALL ^ E_NOTICE);

// DECODE THE INCOMING STRING
$data = base64_decode($_GET['dt']);

// CREATE AN IMAGE RESOURCE - CHOOSE THE SIZE THAT BEST MATCHES YOUR PAGE STYLE
$im   = imagecreate(46,13);

// WHITE BACKGROUND
$bg   = imagecolorallocate($im, 255,255,255);

// GRAY STRIPES
$gray = imagecolorallocate($im, 188,188,188);

// FIREBRICK TEXT
$text = imagecolorallocate($im, 178,34,34);

// ADD THE NUMBER TO THE IMAGE
imagestring($im,5,4,0,$data,$text);

// WRITE A GRAY STRIPE (OR MORE IF YOU CHOOSE)
imageline($im,4,12,38,0,$gray);

// SEND THE IMAGE INTO THE BROWSER OUTPUT STREAM
imagepng($im);
imagedestroy($im);
?>







<!-- THIS HTML GOES IN THE FORM SCRIPT - STYLE IT TO SUIT YOUR PAGE STYLE -->
Type <img style="display:inline;" src="captcha_number.php?dt=<?php $x = mt_rand(1000,10000); echo base64_encode($x); ?>" /> here:
<input name="_newCode" type="text"   maxlength="64" size="6" autocomplete="off" />
<input name="_newMd5"  type="hidden" value="<?php echo md5($x); ?>" />







<?php // THIS SEGMENT GOES IN THE ACTION SCRIPT TO VALIDATE THE FORM INPUT
if ($_POST["_newMd5"] != md5($_POST["_newCode"]))
{
    // MIGHT WANT TO MAKE THIS USER-FRIENDLY
    die('Security code number did not match');
}

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Just testing to see if a blank like gets modified by the EE code snippet
This is the second line of an EE code snippet.

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Interestingly the code snippet discarded the first blank like, then indented the second line.  Sheesh!  Do they test this stuff?  Anyway, I'll stand by to see what your server does with the RAY_temp_tocacar.php
 script.

Author

Commented:
Thanks very much Ray.  I tried to run the first bunch of code and all I get is:

"The image '....url...' cannot be displayed because it contains errors"

Re; the 3-part code sample, I get something a bit different:

"Type [then a box with an image similar to a document torn in half inside it] here: [input field]"

I'm going to keep playing around with it to see if I can get it to work.  Will post again tomorrow with the results.

Thanks again for all your help.

Author

Commented:
This is the png file that is generated by the RAY_temp_tocacar.php script - see attached.
testimage.png
Most Valuable Expert 2011
Top Expert 2016

Commented:
Try visiting this URL and tell me what you get, please.
http://www.laprbass.com/RAY_temp_tocacar.php

If that works for you, there may be something wrong in your PHP installation.  Suggest you install this script and post a link to it.   You do not have to leave it online long - I just want to check the GD information.
<?php phpinfo(); ?>

Open in new window

I also find your PHP errors for the image unusual and can not understand the "Blank" spaces before the PNG image data. Perhaps it has something to do with the CLASS it's in?
BUT, I have used the PEAR Text_CAPTCHA, and will give you some code for that using a string search for the character 137 PNG start, and remove the extra data before it, This is ONLY to test your PEAR Text_CAPTCHA Independent of your "class UtilityController extends CustomControllerAction" setup.
You will need to add your font pathe and file name also change the
<img src="vimage.php?img=doit" />
to your php script name
<?php
ini_set("display_errors", 0);// you REALLY should not need this, I do not
$img = (empty($_GET['img'])) ? '+' : $_GET['img'];
if ($img !='+') {
  // You must have the correct PATH in this require_once
	require_once 'Text/CAPTCHA.php';
	$aPhrase = 'A Phrase';// this is only for test
	$imageOptions = array('font_size'=> 22,'font_path'=> '/home/user/font/', // place YOUR FULL PATH
		'font_file'=>'empty.ttf','text_color'=>'#CC3333','lines_color'=>'#0070A0','background_color'=>'#55B5FF');
	$options = array('width'=>186,'height'=>72,'phrase'=>$aPhrase,'output'=>'png','imageOptions'=>$imageOptions);

	$cap = Text_CAPTCHA::factory('Image');
	$retval = $cap->init($options);
	if (PEAR::isError($retval)) {echo 'ERROR c->init, '.$retval->getMessage(); exit;}

	$phrase1 = $cap->getPhrase();// not used here
	//$png = '  '; // for test
	//$png .= $cap->getCAPTCHAAsPNG();
	$png = $cap->getCAPTCHAAsPNG();
	if (PEAR::isError($png)) {echo 'ERROR getCAPTCHAA, '.$png->getMessage(); exit;}
    // I added the following to clear the added spaces brfore the PNG data
    // You REALLY should NOT need this, I do not need it for my server
	if ($png[0] != chr(137)) {$sp=strpos($png,chr(137));
	if ($sp !== false) $png = substr($png, $sp, 200000);
	}
	//header('Content-Type: image/png');
	echo $png;
	exit;
	}
?>
<html><head><title>Captha Image test</title></head><body bgcolor="#D3E7F2" twxt="#000000"><h2>A test for the Captha Image</h2>
<img src="vimage.php?img=doit" /><br />
</body></html>

Open in new window

Author

Commented:
@Ray
When I click the link, I see "1234" in red with a grey diagonal line through it.  Looks like there's something wrong with my PHP.... (or my PEAR installation?; I did this by running the go-pear command).  I can't publish a link to my phpinfo page that is visible to the outside world, so I've saved it as a PDF instead and attach it here (I hope that's not a security risk?).   I can uninstall PHP and re-install it, but I'll wait until I hear back from you incase you think it all looks OK.

@Slick812
Thanks for posting your code.  I'll give this a try and will let you know what I get.  Regarding the blank space in the PNG view source; interestingly, it's only there when I shut off the errors using ini_set().  If the errors are allowed to show, and I view source, the errors appear, then the PNG characters begin but the start (%PNG) is not indented; maybe the blank space just indicates the hidden errors?

phpinfo.pdf
I have NO direct experience with php.ini and the E_STRICT error reporting, but in php 5.3 there are some changes that make it different than the 5.2 versions that my servers are running. I would think it would be to your benefit to remove the E_STRICT setting in php.ini? You might look at -
http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
to see the manual info. I would guess many of your current difficulties would go away if you did that. It's hard enough to lean PHP, but the E_STRICT should only be on if you are specializing in contemporary, newer PHP standards, and the PEAR libraries do not seem to hold those standards.

Author

Commented:
@Slick812
Thanks for your input.  I'm going to recreate my development environment on a Mac tomorrow to see if I can get the CAPTCHA to appear.  If it works, I'll just stick with that.  I'll post the results..... then award points.
Most Valuable Expert 2011
Top Expert 2016

Commented:
The phpinfo() for the GD library looks fine, and if you see the 1234 you are seeing an inline PNG.  So if that works on my server but not on your server it _may_ be worth reinstalling PHP.  But I agree that E_STRICT is probably a mistake unless you control all of the code.  E_STRICT may be causing a message to be generated somewhere that is making the header() command fail.

Author

Commented:
@Ray
Thanks for checking my PHP setup; I'll do a PHP reinstall tomorrow and see if that helps (I'll also turn off the E_STRICT error reporting).  I'll let you know how I get on.  I'm also going to try setting things up on a Mac to see if that works.  Thanks very much for all your help with this.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Glad to help, and I hope we can get over the hump here.  A frequent default error reporting setting is E_ALL ^ E_NOTICE.  I like to use E_ALL because I an anal about things like undefined vars.  Just a personal preference.

Author

Commented:
OK, I've recreated my setup on a Mac (reinstalling PHP using Marc Liyanage's entropy 5.3), taking extra care to ensure GD is installed and enabled and all the necessary CAPTCHA files are in my Pear library.  I have also set the error_reporting in php.ini to E_ALL ^ E_NOTICE.  Unfortunately, I still can't generate an image.  I thought it might be the font that was causing problems, so I checked the permissions (Read & Write for all) and downloaded a few others.  Still no joy.

@Slick812
I tried your test code, but only got a broken image icon in Safari and nothing in Firefox (except the text that is outputted at the top of the page).

This is very frustrating, but I'm reluctant to give up until it's fixed.

I think the CAPTCHA function itself is working as it is generating some raw PNG data, it's just the stuff it produces is unreadable by my browser or any graphics application.  This makes me thing the problem lies with whatever is responsible for producing/ handling the PNG data (that's GD, right?). Going forward I guess the questions are:

1.  Is there a way I can generate simple images using GD that don't require CAPTCHA or a font file?  If I can get something simple and basic to appear, then it would prove that GD is in fact working, thereby suggesting another culprit....

2.  Is there a diagnostic test I can run from the command line that would pick up any problems with my GD extension?  I run the following script in my browser and get the attached results:


<?php

if(extension_loaded('gd'))
{
    echo 'GD is loaded!';

    if(function_exists('gd_info'))
    {
        echo ' Info: ';

        echo '<pre>' . print_r(gd_info(), true) . '</pre>';
    }
}
else
{
    echo 'GD is not loaded';
}

?>

Open in new window

pear-gd-test.php.html
I looked at the pear-gd-test.php.html , and I did not expect or did I see anything that gives any usable (to me) bug fix info. I realize that you are trying to figure in anything that you can think of to fix this. I am so sorry to hear that the elimination of the E_STRICT directive did not give you a functioning php call for the methods you are trying to learn.
AS to a GD image code test see, code below, this does NOT do a PHP image data, but places the PNG images into a file.
If you do NOT get an image file that displays correctly in your browser - you should be able to load this file a HEX editor, or just a text editor and see if there are NON IMAGE data segments. At this point, I do not see that your "Apache, PHP, MySQL" software installer is worth your time or trouble (my very stupid opinion). Perhaps you might consider an older version before php 5.3, another alternative or asking about this in the EE - Web Development - Web Servers - Apache Web Server , section.

<html><head><title>Trans PNG test</title></head><BODY BGCOLOR="#E3F7FF"><h2>GD Transparent PNG Image test</h2>
<?php
$image=imagecreatetruecolor(128, 72);
$back = imagecolorallocate($image, 255, 0, 0);
imagefilledrectangle($image,0,0,128,72,$back);
imagepng($image,'images/png1.png');//your own path and below in <img src
imagedestroy($image);
?>
<p><img src="images/png1.png"></p>
</body></html>

Open in new window

I just remembered, about an alternative , just for PHP development testing, which, I guess is your requirements for PHP. There is a portable application called "phpWAMP" , which runs a PHP testing environment on your windows machine, without any "Apache server" being set on your machine. I have not used this recently, but it worked well right out of the box for me with GD, MySql and other PHP ext already installed. However, I do not think it comes with any PEAR already installed. You can find out some at -
http://www.geardownload.com/internet/phpwamp.html

I can not give this a high recomendation, because I did not use it very much, but it seems to work.

Author

Commented:
MAJOR BREAKTHROUGH!  (but still not quite working)

I went right back to basics and figured out how to display a coloured box as a PNG in the browser.  Then I added a line to it, then some text, the some text using a specified font.  It all worked, which means GD is working as expected.

I then took my UtilityController script and stripped out all the stuff relating to the Zend Framework, leaving me with a stand-alone CAPTCHA script which I called directly from localhost root.  This worked (YAAAAAAY).  

GD works + CAPTCHA works = Zend is the problem.

I went back to my UtilityController script, which still wasn't working, and commented out/ back in the Zend stuff.  Still not working.  I var_dumped some Zend stuff throughout the class to check that objects existed where they were supposed to; they do.  

So, I took another look at my bootstrap file (index.php) which eveything goes through.  This is the big breakthrough: when I comment out the section shown in the code snippet below, the CAPTCHA displays in the browser(!).  When I uncomment it, it stops working again.  This must be where the problem lies...I guess.  

I have sifted through the various Zend classes to see if I can figure out how it all strings together.  There can't be anything wrong with them (surely??) as millions of people around the world must be using these classes without any serious problems.

I have re-attached my bootstrap and UtilityController files.  Can you please take another look to see if you can spot anything odd in them or suggest anything I should change to make things work?

Thanks very much for all your help everyone, I really appreciate it!


*SECTION OF CODE FROM INDEX.PHP WHICH, WHEN COMMENTED OUT, ALLOWS THE CAPTCHA FROM UTILITY CONTROLLER TO DISPLAY*

// setup the view renderer
$vr = new Zend_Controller_Action_Helper_ViewRenderer();
$vr->setView(new Templater());
$vr->setViewSuffix('tpl');
Zend_Controller_Action_HelperBroker::addHelper($vr);

Open in new window

index.php
UtilityController.php
WOW, you have certainly learned so much about PHP debugging, in your efforts with this. I am glad you have some success at last. -
I have not used the Zend_Controller_Action_Helper_ViewRenderer, But you might consider to change the -
$vr->setViewSuffix('tpl');       // have no clue what a .tpl extention may be for?
to-
$vr->setViewSuffix('php');

I do not have any Idea what the setViewSuffix() might do, but half-ass info is given in this page -
http://www.zendframework.com/manual/en/zend.controller.actionhelpers.html

You use several many Zend methods such as - Zend_Config_Ini , Zend_Auth , Zend_Controller_Front, each of these have many options and uses, seems so complex to try and learn, if you are a beginner in PHP and do not need a complex many optioned framework for a website.

I never thought to consider "Zend Framework" as a problem, since you did not mention it in your statements here, but maybe I missed something. As far as I'm concerned (my opinion), The "Zend Framework" is a big complicated bundle of stuff that only has use for LARGE non-simple framework development, I would not recommend to any that are beginners in PHP development. I think that users of PHP need to know alot of the basic methods, before they use complex PHP code classes. I also do not think the PEAR should be learned, until one has experience in general PHP methods and coding practices. I do not think the PEAR CAPTCHA is a not very good one for overall security benifits against web image scanners. You said you needed basic code for the GD image creation, it seems that you should be learning that sort of thing, before banging your head on the Zend Framework monster. But I am usually clueless about what others may need.

Author

Commented:
@Slick812
Thanks very much for all your help and advice.  I hear what you're saying about Zend and Pear; it's definitely been a steep learning curve.  I'm only dipping into it as I follow along with the book I'm trying to learn from (I have a large and complex application to convert from Filemaker to PHP/MySQL so I have to learn all this stuff, and quickly!  I'm trying to learn Symfony and YUI too as a possible alternative to Zend, Smarty and scriptaculous).  

The great thing about this problem is that I have forced myself to learn A LOT (I've been trying to figure this out for about 10 days!) and it's all making much much more sense to me now.  

The 'tpl' suffix in setViewSuffix is so Zend's ViewRenderer can utilise the Templater object in setView() to produce a Smarty template instead of Zend's own template.  I think this is where my problem is.  It's all mega complicated but, as I say, the mist is beginning to clear.  I think my problem is something really small but just invisible to me right now.  I'm going to keep going with it until I get there.  In the meantime, I'll close this question and award points.  When I finally figure it out, I'll post the solution here.  

Thank you to all who helped!

Author

Commented:
Great help, thanks.  I learned a lot!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial