I couldn’t find a succinct way to summarise the question in the title, allow me to elaborate:
I have a website that uses a PHP script “getImg.php” that takes an image binary object from my database and display it when called by the HTML img tag on a separate page.
I would like to log the number of times people view images so I added a simple line to increment the ‘views’ property for the appropriate image.
I thought this would be simple, but it turns out that it increments twice. My bodgy way around this was to make the ‘views’ column a float and increment by 0.5 to result with a 1 increment. However, I viewed my database today to find 0.5 in some images!
When I comment out the end print it works properly. I assumed the call from the HTML tag plus the script itself counts for two calls? But this doesn’t seem to be the case with other people.
Is this just my set up?
<?php
# Connect to db
include('db.php');
# Get ID
$id = $_GET['id'];
if(!is_numeric($id)) exit;
$q = $db->prepare("SELECT tNail,image,format FROM gallery WHERE id = '$id'");
$q->execute();
$row = $q->fetch(PDO::FETCH_ASSOC);
if(array_key_exists("thumb", $_GET))
$img = base64_decode($row["tNail"]);
else
{
$img = base64_decode($row["image"]);
# Add to views if not thumb
// 0.5 because script called twice due to print?
$db->query("UPDATE gallery SET views = (views + 0.5) WHERE id = '$id'");
}
switch($row["format"])
{
case ".jpg":
header("Content-type: image/jpeg");
break;
case ".png":
header("Content-type: image/png");
break;
}
print $img;
?>
Thanks for any help.
This seems to be a brwoser issue. Browsers like Chrome could prefetch the images so it is loaded once and if the user clicks on a link to a image – it is loaded twice.
Check:
Load a image with your browser and then check your apache access.log and if you see 2 request at the same time it is a browser issue.