加载图像时运行脚本

时间:2013-08-12 13:46:27

标签: web-applications

有没有办法在加载图片时运行代码?

例如,如果我的图像托管在www.mydomain.com/image.png,如果有人执行此链接,则会显示图像,因为这是一个图像文件。但是,当有人试图查看图像时,我可以运行一组代码吗?

像。

当我打开运行www.mydomain.com/image.png时,它应该执行类似

的操作
<?php
  mail("myemail@mydomain.com", "image opened", "image opened by".$Server['addr']);
?>

我发现网上提供了多种此类服务,但我无法理清在尝试执行图像文件时如何执行代码文件。

有人能简单介绍一下这将如何锻炼吗?我可以自己编码

2 个答案:

答案 0 :(得分:0)

是使用图片元素的onload event

客户端:

<img src="..." onload="JavaScript_Code">

img = document.getElementById("Image_Id")
img.onload = function(){SomeJavaScriptCode};

服务器端(index.php):

<?php
// do some works with the $_Get["path"]
header('Content-Type: image/png');
readfile($_Get["path"]);
exit;

和图片网址将是* index.php?path = Path_to_png_image_file *或者您可以执行URL_Rewriting删除索引?部分网址

答案 1 :(得分:0)

在稍微浏览之后,看起来处理此问题的最佳方式可能是使用mod_rewrite,如果它可用的话。

设置类似

的规则
# Enable Rewriting  
RewriteEngine on  

# Rewrite user URLs  
#   Input:  images/image.png/  
#   Output: images.php?f=image.png  
RewriteRule ^images/(\w+\.png)/?$ images.php?f=$1  

然后,使用php documentation中给出的示例来提供图像:

<?php

$filename = $_GET['f'];

if (!file_exists($filename))
{
    header('HTTP/1.0 404 Not Found');
    include('image404.php'); //or something similar if you want a nice error message
    exit();
}
else
{
    mail("myemail@mydomain.com", "image opened", "image opened by".$Server['addr']);

    $fp = fopen($_GET['f'], 'rb');

    header("Content-Type: image/png");
    header("Content-Length: " . filesize($name));

    fpassthru($fp);
}

请注意,它要求您从www.mydomain.com/images/image.png这样的子目录中提供文件,但它避免了将所有png文件设置为由php处理的问题。

您可能需要考虑是否需要额外的清理:例如,您可能希望删除文件名中的斜杠和.. - mod_rewrite如何处理它们需要检查。

相关问题