Reputation: 6697
Here is my code:
// captcha.php
<?php
session_start();
$min=0;
$max=9;
$captcha_token='';
for($i=1; $i<=5; $i++){$captcha_token .= rand($min,$max).' ';}
$_SESSION['captcha'] = str_replace(" ","",$captcha_token);
$im = imagecreatetruecolor(110, 34);
$red = imagecolorallocate($im, 245, 245, 245);
imagefill($im, 0, 0, $red);
$text_color = imagecolorallocate($im, 80, 80, 80);
imagestring($im, 8, 15, 9, $captcha_token, $text_color);
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>
And I use it like this:
<img src="../../files/captcha.php" class="captcha_pic" alt="Captcha" />
It works as well. As you know, that is a http request. I mean I can open that image like this:
http://localhost/myweb/files/captcha.php
Now I want to change the place of file
directory and put it out of the document root. So I cannot access captcha.php
through a http request. I have to use absolute path to get it. How?
Noted that this doesn't work:
<?php
$img = include __DIR__ . "/../../files/captcha.php";
?>
<img src="<?=$img?>" class="captcha_pic" alt="Captcha" />
Upvotes: 0
Views: 51
Reputation: 7485
You could place your functionality in a file, that you then include and use to generate a base64 encoded data image:
<?php
function createBinaryImageCaptcha($text) {
$im = imagecreatetruecolor(110, 34);
$red = imagecolorallocate($im, 245, 245, 245);
imagefill($im, 0, 0, $red);
$text_color = imagecolorallocate($im, 80, 80, 80);
imagestring($im, 8, 15, 9, $text, $text_color);
ob_start();
imagejpeg($im);
imagedestroy($im);
return ob_get_clean();
}
function createDataImage($binary) {
return 'data:image/jpeg;base64,' . base64_encode($binary);
}
Then require above that you can place where you like. To use:
$img = createDataImage(createBinaryImageCaptcha('helloearth'))
?>
<img src="<?= $img ?>" alt="captcha text">
Bear in mind that not all browsers support data uris for images.
Which browsers support data URIs and since which version?
And please consider captcha accessibility.
Upvotes: 1