我开始编写自己的图像主机,但我有一个小问题:
如果您通过浏览器直接查看链接(例如 Domain.com/img/123),我想显示一个 HTML 页面,如果您通过以下方式嵌入链接,我想显示一个图像
<img src="Domain.com/img/123">
Run Code Online (Sandbox Code Playgroud)
以方便使用。
是否可以检测链接是直接查看的还是用PHP嵌入的链接?
您可以使用htaccess文件来实现此目的:
当浏览器加载嵌入图像时,他已经知道期望的格式,因此他会HTTP:Accept在请求文件时将此信息添加到标头中。(或者至少将其减少为任何图像类型)
如果浏览器直接访问文件(地址栏中的 url),他不知道这一点,因此他将添加text/html到HTTP:Accept标头。
从铬中提取:
直接的:Accept text/html, application/xhtml+xml, */*
嵌入:Accept image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5
使用此信息来捕获直接访问情况:下面的示例将重定向访问http://localhost/test/myimage.gif到index.php?url=/test/myimage.gif.
RewriteEngine on
RewriteCond %{REQUEST_URI} .*\.gif # redirect gifs
RewriteCond %{REQUEST_URI} !.*index\.php # make sure there is no loop
RewriteCond %{HTTP:Accept} .*text/html.* # redirect direct access
RewriteRule (.*) http://localhost/test/index.php?url=$1 [R,L]
Run Code Online (Sandbox Code Playgroud)
另一个文件http://localhost/test/test.php可以正确使用<img src="http://localhost/test/myimage.gif" />不会发生重定向,因为不会Accept: text/html发送任何内容。
请记住,这有点不好测试:一旦将图像嵌入到某处,当您直接访问图像时,浏览器缓存将不再加载数据。因此,看起来可以直接访问。但是,如果您按 F5 刷新缓存的图像,则重定向将适用。(保持调试工具打开以禁用缓存)
至于你的评论。我忽略了你想随时使用人工 url 来呈现图像。这改变了htaccess ofc的设计方式。
以下 htaccess 的行为应符合您的预期:
/2537263),则认为有资格进行重写。wrapperpage.phpimage.php访问:
RewriteEngine on
RewriteCond %{REQUEST_URI} /\d+$
RewriteCond %{HTTP:Accept} .*text/html.*
RewriteRule ^(.*?)$ http://localhost/test/wrapperpage.php?id=$1 [R,L]
RewriteCond %{REQUEST_URI} /\d+$
RewriteCond %{HTTP:Accept} !.*text/html.*
RewriteRule ^(.*?)$ http://localhost/test/image.php?id=$1 [R,L]
Run Code Online (Sandbox Code Playgroud)
注意:如果您省略该[R]选项,用户将看不到 url 中反映的重定向。
我使用的示例页面代码:
包装页.php:
THIS IS MY WRAPPER PAGE:
<br />
<img src = "http://localhost/test/<?=$_GET["id"]?>" />
<br />
IMAGE IS WRAPPED.
Run Code Online (Sandbox Code Playgroud)
image.php(我假设你确定图片的逻辑就在那里)
<?php
//Load Image
$id = $_GET["id"];
//pseudoloading based on id...
// loading...
// done.
$image = imagecreatefromgif("apache_pb.gif");
//output image as png.
header("Content-type: image/png");
imagepng($image);
?>
Run Code Online (Sandbox Code Playgroud)
所以:
http://localhost/test/1234在浏览器中->wrapperpage.php?id=1234http://localhost/test/1234嵌入->image.php?id=1234http://localhost/test/image.php?id=1234-> 返回 png 图像。