Ali Hesari Ali Hesari - 3 months ago 17
PHP Question

How to use captcha in wordpress plugin

I create a wordpress plugin. This plugin show a submit form in wordpress theme. i use this php captcha code in my wp plugin:

function create_image() {
$md5_hash = md5(rand(0,999));
$security_code = substr($md5_hash, 15, 5);
$_SESSION["security_code"] = $security_code;
$width = 100;
$height = 35;
$image = ImageCreate($width, $height);
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 2, 0, 0);
$blue = ImageColorAllocate($image, 87, 20, 186);
$grey = ImageColorAllocate($image, 204, 204, 204);
ImageFill($image, 0, 0, $blue);
ImageString($image, 5, 30, 8, $security_code, $white);
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
header("Content-Type: image/jpeg");
Imagepng($image);
ImageDestroy($image);
}


and use captcha in img tag:

<img class="captcha" src="<?php create_image() ?>">


But when i use this plugin in my theme, don't worked!

Answer

Your image tag will, when you render it, say

      <img class="captcha" src="<<a whole bunch of binary stuff>>">

Why? because your create_image() function emits the image inline using the single-parameter form of Imagepng().

Instead, you need to emit the image to a .png file, then mention that file's name in your <img ... /> tag.

You could change the last few lines of your function to work like this.

   ...
   ImageRectangle($image,0,0,$width-1,$height-1,$grey); 
   $file = "tmp-" . rand() . ".png";
   Imagepng($image, $file);
   return "/" . $file;
}

This will make your function create a png file with a random name and then return the path to that file to be used in your <img .../> tag.

This will take some debugging. The way I have written it, it assumes that you are able to write to the current working directory. You probably need to write to some temp directory that's accessible to your web server instead.

Also, these image files will pile up. You'll need to cook up some cron job or something to clean out the old ones.