简体   繁体   English

如何访问超出文档根目录的文件?

[英]How can I access a file which is out of document root?

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. 如您所知,这是一个http请求。 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. 现在,我想更改file目录的位置,并将其放在文档根目录之外。 So I cannot access captcha.php through a http request. 因此,我无法通过http请求访问captcha.php 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" />

You could place your functionality in a file, that you then include and use to generate a base64 encoded data image: 您可以将功能放在文件中,然后将其包含并用于生成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);
}    

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. 请记住,并非所有浏览器都支持图像的数据uri。

Which browsers support data URIs and since which version? 哪些浏览器支持数据URI,以及从哪个版本开始?

And please consider captcha accessibility. 并且请考虑验证码可访问性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM