开发者

Tracking image views - PHP

开发者 https://www.devze.com 2023-02-01 22:22 出处:网络
I\'d like for my app to be able to tell if an image hasn\'t been viewed in the last 30 days and remove it开发者_如何学Go (along with data in the DB associated with it). I know you can have PHP read an

I'd like for my app to be able to tell if an image hasn't been viewed in the last 30 days and remove it开发者_如何学Go (along with data in the DB associated with it). I know you can have PHP read and output the image dynamically but I've heard its quite taxing on the system. Is there a way to for me to track these hits even when the image is viewed directly? (would htaccess be able to do this?) Thanks in advance.


For .htaccess something like this...

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

And for 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


You can parse out the HTTP logs and do this analysis post-factum.

That said, I'd still recommend going with a "dynamic PHP file outputting an image" approach - note that the PHP file can simply stream out a file. Yes, it'll be slower than not going through PHP at all, but it won't be a significant performance hit on your system.


You can create a script that fetches images and pings your database to show that the image has been viewed. By setting the return type of your script to image/jpg you can just use this script instead of accessing images directly:

<?php
//simplified image display script

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

?>

Then use:

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


As far as I know, you'll need to have a database for this.

Sample schema:

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;

There could be errors here, I'm just giving you a general idea...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号