[英]How can I access a file which is out of document root?
这是我的代码:
// 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);
?>
我这样使用它:
<img src="../../files/captcha.php" class="captcha_pic" alt="Captcha" />
它也可以。 如您所知,这是一个http请求。 我的意思是我可以像这样打开该图像:
http://localhost/myweb/files/captcha.php
现在,我想更改file
目录的位置,并将其放在文档根目录之外。 因此,我无法通过http请求访问captcha.php
。 我必须使用绝对路径来获取它。 怎么样?
注意,这不起作用:
<?php
$img = include __DIR__ . "/../../files/captcha.php";
?>
<img src="<?=$img?>" class="captcha_pic" alt="Captcha" />
您可以将功能放在文件中,然后将其包含并用于生成base64编码的数据映像:
<?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);
}
然后要求以上所述,您可以放置在自己喜欢的地方。 使用方法:
$img = createDataImage(createBinaryImageCaptcha('helloearth'))
?>
<img src="<?= $img ?>" alt="captcha text">
请记住,并非所有浏览器都支持图像的数据uri。
并且请考虑验证码可访问性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.