簡體   English   中英

如何訪問超出文檔根目錄的文件?

[英]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。

哪些瀏覽器支持數據URI,以及從哪個版本開始?

並且請考慮驗證碼可訪問性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM