【问题标题】:Tracking image views - PHP跟踪图像视图 - PHP
【发布时间】:2011-06-01 07:49:03
【问题描述】:

我希望我的应用能够判断图像是否在过去 30 天内未被查看并将其删除(连同与之关联的数据库中的数据)。我知道您可以让 PHP 动态读取和输出图像,但我听说它对系统造成了很大的负担。即使直接查看图像,有没有办法让我跟踪这些点击? (htaccess 能做到这一点吗?)提前致谢。

【问题讨论】:

  • 不建议使用 PHP,使用 apache 日志,对服务器的影响最小

标签: php image analytics tracking


【解决方案1】:

对于 .htaccess 类似的东西...

RewriteRule ^image/(.*)$ image.php?id=$1

对于 PHP...

$id = $_GET["id"]; //don't forget to sanitize
mysql_query("UPDATE images SET views = views + 1 WHERE image = '$id'"); //update no of views
header("Content-Type: image/jpeg"); //send image header
readfile($id); //output file to browser

【讨论】:

  • 我想补充一点,这肯定需要大量清理。想象一下有人用类似 ?id=/etc/passwd 的东西来敲击这个脚本
【解决方案2】:

您可以解析出 HTTP 日志并在事后进行分析。

也就是说,我仍然建议使用“动态 PHP 文件输出图像”方法 - 请注意,PHP 文件可以简单地流出文件。是的,它会比完全不使用 PHP 慢,但它不会对您的系统造成重大的性能影响。

【讨论】:

    【解决方案3】:

    您可以创建一个脚本来获取图像并 ping 您的数据库以显示该图像已被查看。通过将脚本的返回类型设置为image/jpg,您可以只使用此脚本而不是直接访问图像:

    <?php
    //simplified image display script
    
    $imagepath="phpimages/$id.jpg";
    $db->pingImage($id);
    $image=imagecreatefromjpeg($imagepath);
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    
    ?>
    

    然后使用:

    <img src='fetchimage.php?id=478' alt='tracked image' />
    

    【讨论】:

      【解决方案4】:

      据我所知,您需要为此建立一个数据库。

      示例架构:

      Images
        id (int, PK)
        path (text)
        hits (int)
      

      PHP:

      // get_image.php
      // note, this is just an example and I'm not considering security or hacking attempts
      $sql = mysql_query('SELECT * FROM images WHERE id = '.$_GET['id']);
      $img
      
      if(mysql_num_rows($img) == 1)
        while($row = mysql_fetch_assoc($sql))
          $img = $row;
      else
        // handle some error
      
      mysql_query("UPDATE images SET hit = hits + 1 WHERE id = ".$_GET['id']);
      $img = file_get_contents($img['path']);
      header('image/jpg');
      echo $img;
      

      这里可能有错误,我只是给你一个大概的想法......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多