1

I'm not sure I understand quite how this works. For a website form I'd like to generate a random captcha image and display it along with the form. So ideally I would like something along those lines:

<form action="post.php" method="post">
  ...
  <?php create_captcha(); ?>
</form>

While I do have a function which creates an image resource in PHP (link)

function create_captcha() {
  $w = 60; $h = 30;
  $img = imagecreatetruecolor($w, $h);
  ...
  //header("Content-Type: image/jpeg");
  imagejpeg($img);
}

I can't quite figure out how to output that image directly onto the website as part of the HTML form. My suspicion is that I'll have to save it into a temporary file captcha.jpg and then generate a <img src="captcha.jpg" /> into the website.

Is there a more elegant way without using a temporary image?

Jens
  • 8,423
  • 9
  • 58
  • 78

2 Answers2

3

use your captcha generation file path as source of IMG tag

<img src="http://domain.com/your-captcha_generating-file-path" />
San
  • 632
  • 4
  • 13
  • Wait.. that simple? I stuffed the body of the `create_captcha()` function into its own captcha.php file, and simply call it from the form with a ``. Works like a charm :) – Jens Jul 11 '13 at 13:29
  • How can I add `header()` to this? I would like to set `header("Cache-Control: no-cache, must-revalidate");` to ensure that the capture image isn't cached. – Jens Apr 30 '14 at 02:49
3

You could do something like this:

function getCaptcha() {

    // Begin output buffering
    ob_start();

    // generate the captcha image in some magic way
    $w = 60; $h = 30;
    $img = imagecreatetruecolor($w, $h);
    imagejpeg($img);

    // and finally retrieve the byte stream
    $rawImageBytes = ob_get_clean();

    return "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
}

By using a Base64 encoded data source in your img tag, you won't have to store any temporary files at all.

ciruvan
  • 5,143
  • 1
  • 26
  • 32
  • Thanks! I do remember embedding image data into the website (way back when) but I couldn't figure out how to do this in PHP. Thanks for the code above though, it would be a good solution if the @San's wouldn't be cleaner. – Jens Jul 11 '13 at 13:31
  • You're welcome. As a matter of fact, I've upvoted @San's answer as well cause it's simpler. :D – ciruvan Jul 11 '13 at 13:35
  • Thanks bro. It saves my lot of time. – Aniket Singh Dec 15 '18 at 09:26