我想在通过脚本查看图像后获得查看器的HTTP_USER_AGENT
。
这是目录
/www
|-- /other.org
|-- /example.com
|-- /sub
|-- .htaccess
|-- agentlog.php
|-- /i
|-- photo.png
我已经将图像文件和脚本分离到不同的文件夹中。所有文件的根目录都在域的子目录中。因此http://example.com/sub
,图像被存储在http://example.com/sub/i
。.htaccess
文件将把所有图像重定向到一个PHP文件,该文件获取HTTP_USER_AGENT
并将其存储在数据库中,还通过一个不会被.htaccess
重定向的子域显示图像。
更详细地说,用户在浏览器中键入http://example.com/sub/photo.png
,对查看器来说,它看起来就像是图像,查看器不会注意到任何其他内容或任何重定向。然而,当用户输入时会发生什么
.htaccess
将检查http://example.com/sub/i/photo.png
中是否存在photo.png
,如果图像存在,则在http://example.com/sub/agentlog.php
将请求重定向到名为agentlog.php
的文件,然后agentlog.php
将记录并保存到数据库,并显示photo.png
到http://i.example.com/photo.png
,其中http://i.example.com
指向/www/sub/i
。
这是.htaccess
文件
RewriteEngine On
RewriteCond %{HTTP_HOST} !^i'. [NC]
RewriteCond %{DOCUMENT_ROOT}/i/$1 -f
RewriteRule ^(.+'.(?:jpe?g|png|gif))$ agentlog.php [NC,L]
这是没有sql代码的agentlog.php
文件
<?php
$path = $_SERVER['REQUEST_URI'];
$agent = $_SERVER['HTTP_USER_AGENT'];
$ext = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_EXTENSION);
$filename = basename($path);
header("Content-Type: image/$ext");
$img = "http://i.example.com/$filename";
readfile($img);
一切都很好,除了图像没有真正显示出来,.htaccess
重定向。显示
�PNG IHDR�^���� �IDATx��ݯ��u���............
而不是实际图像本身。
如果我直接访问图像,它可以正常工作,所以我认为问题出在.htaccess
上,但我不知道该写什么其他规则来实现这一点。
如果需要其他进一步的信息,我很乐意补充。我该如何解决这个问题?或者有什么方法可以做到这一点吗?我已经放入了内容标题,但不确定为什么它不起作用。
如果您正在使用结束标记?>
,请检查后面是否有空格或换行符。省略结束标记被认为是一种良好的做法。
编辑
试试这个:-
$img = "http://i.example.com/$filename";
header("Content-Type: image/$ext");
header('Content-Length: ' . filesize($img));
ob_clean(); // Clean (erase) the output buffer.
flush(); // Flush system output buffer.
readfile($img); // Output the file to browser.
exit; // Stop execution of the script
一切都很好,除了图像没有真正显示出来,.htaccess重定向。显示
�PNG IHDR�^���� �IDATx��ݯ��u���............
这是一个标头错误(mime类型错误)-text/plain而不是image/。。。
无论如何,你的.htaccess在我的环境中不起作用应该是这样的:
RewriteEngine On
RewriteCond %{REQUEST_URI} (.+'.(?:jpe?g|png|gif))
RewriteRule ^(.+'.(?:jpe?g|png|gif))$ agentlog.php [NC,L]
PHP代码可以类似于
<?php
$path = $_SERVER['REQUEST_URI'];
$agent = $_SERVER['HTTP_USER_AGENT'];
$ext = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_EXTENSION);
$filename = basename($path);
header("Content-Type: image/".$ext);
readfile($filename);
?>