0

please let me know if you know how to develop what I really want to do.

I have a code which creates an image (similar to a captcha) like this :

/* createImg.php */


class createImg{
public function __construct(){
    /*stuff here*/
}

public function showImg(){
    /*stuff here*/
    header("Content-type: image/png");
    imagepng($image);
    imagedestroy($image);
}
}
$img = new createImg();
$img->showImg();

And what I do to create the image is something like :

/* index.php */
echo '<img src="createImg.php" />';

Everything works fine but what I would like to do is the following thing but I don“t know how to implement it:

/* index.php */
$img = new createImg();
//and now something like this
echo '<img src="$img->showImg()" />';

The problem I get is that, if I use this way, I got the image in the main screen due to the header in the function. Is there any way to do what I want to do ?

themazz
  • 1,107
  • 3
  • 10
  • 29

1 Answers1

0

In general, you can't output raw image data in the middle of an HTML page, which is what your echo statement there is attempting to do.

There are limited mechanisms, such as the data: URI scheme, but they have important limitations to be aware of, and are probably not appropriate for most situations.

Instead, you will need to have some way of generating a URL for your image which includes enough information to create the right image. For a simple case, this could just be something like "/img.php?width=100&height=100&colour=red".

Since you describe your use case as "similar to a CAPTCHA", this will presumably be more complex, and may also need to be obfuscated rather than just spelling out the contents in the URL. You'll therefore need to store something at the server end; I can think of a few approaches:

  1. You could write to the PHP session the image data, or the input needed to generate it. The usual problems with sessions, such as locking, apply.
  2. You could save the data to a database, giving it a unique key; the image URL could then be something like "/img.php?unique_id=42".
  3. You could save the resulting image to disk, giving it a unique filename. This would obviously need some sort of "garbage collection" mechanism, or your disk will eventually fill up with all of these image files.
IMSoP
  • 89,526
  • 13
  • 117
  • 169