如何在没有真实URL的情况下返回PHP中的文件?



我这里有图像文件

/var/www/img/timetable.jpeg

网址是

www.mydomain.com/img/timetable.jpeg

但是我不希望用户知道真实的URL,我希望用户像这样访问文件

www.mydomain.com/get/timetable.jpeg

所以我使用 PHP 框架来拦截请求,例如无脂肪

$f3->route('GET /get/@filename',
function($f3) {
$filename=$f3->get('PARAMS.filename');
// here return/redirect the file
}
);

但我不想使用这种方式。

$f3->route('GET /get/@filename',
function($f3) {
$filename=$f3->get('PARAMS.filename');
$attachment_location = 'img/'.$filename;
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: image/jpeg");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".filesize($attachment_location));
header("Content-Disposition: attachment; filename=".$filename);
readfile($attachment_location);
}
);

我期望这样的东西,但这是重定向,用户会知道 URL

$f3->route('GET /get/@filename',
function($f3) {
$filename=$f3->get('PARAMS.filename');
header("Location: img/".$filename);
}
);

我可以在PHP中做到这一点吗,它被称为Forward吗?

您可以使用几种不同的解决方案来实现此目的。 最简单的方法是使用 Apache 的 .htaccess 重写规则。对图像发出的所有请求都将转到处理请求的映像服务器.php文件。

/get/.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule (.*) image-server.php?file=$1 [QSA,L]
</IfModule>

不要将映像托管在同一目录中。您的图像服务器.php将读取 $_GET["file"] 值并从受保护的目录返回图像。

<?php
# /get/image-server.php
header("Content-Type: image/jpeg");
$secret_location = "/var/www/html/images/timetable.jpeg";
readfile($secret_location);

这是一个基本的使用示例。您应该检查 $_GET["文件"],即。$secret_location="/PATH/{$_GET['file']}";确保映像文件存在,然后readfile()

因此,您的目录结构为:

/get/.htaccess
/get/image-server.php
/secret-location/images/timetable.jpeg

您的任何图像都不会有真实的 URL,因为您将在htdocspublic_html文件夹之外托管图像。

也许这会有所帮助:

function showImage($name){
$file = basename($name);
$path  = 'img/'.$file;
$mime = mime_content_type($path);
$types = [ 'gif'=> 'image/gif', 'png'=> 'image/png', 'jpeg'=> 'image/jpeg', 'jpg'=> 'image/jpeg'];
// if allowed type
if(in_array($mime, $types)){        
if(file_exists($path)){
header('Content-type: '.$mime);
header("Content-Length: " . filesize($path));
//echo file_get_contents($path);           
readfile($path);
}       
}
}

相关内容

最新更新