I would like to have code for an image that counts the number of times the image is viewed, regardless of what site the image is found on. I want to use the img src tag, and hav
Yes you're on a good start. I'd do something like this
<img src="www.mywebsiteurl.com/image_counter.php?src=image.jpg" />
In image_counter.php, take $src = $_GET['src']
for image source.
Then +1 the hit for that image in the database.
Then do
header('Content-type: image/jpeg');
readfile($src);
Your script needs to:
header('Content-Type: image/jpeg');
)readfile( $path_to_image )
);For examples, please see the readfile documentation and Output an Image in PHP.
You can call an image using a URL similar to: www.mywebsiteurl.com/image_renderer.php?url=url_to_image
.
image_rendered.php:
<?php
header("Content-Type: image/jpeg");
$url = urldecode($_GET['url']);
$headers = array(
"GET ".$url." HTTP/1.1",
"Content-Type: text/xml; charset=UTF-8",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache"
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$r = curl_exec($ch);
// you can connect to your database and increment the number of times this image was viewed
echo $r;
?>
Hope this will point you into the right direction.
This is the most barebones version you can have:
<?php
header('Content-type: image/jpeg');
readfile('somepic.jpg');
Something like this should work:
<?php
$file = $_GET['img'];
$path = "images/";
// do an increment of views on the image here - probably in a database?
$exifImageType = exif_imagetype($path.$file);
if ($exifImageType !== false) {
$type = image_type_to_mime_type($exifImageType);
}
header('Content-Type: $type');
echo file_get_contents($path.$file);
Note: this would make something like:
<img src="getimage.php?img=image.jpg" />
show the correct image after incrementing the views.
You could always add some .htaccess to make all calls to /images/anything go through your image file. It'd mean you could keep the URL looking as though it's getting an actual image file (e.g. /images/logo.jpg would be re-written to actually go through getimage.php?img=logo.jpg)
Loading images / files from php is slow than normal loading files.
Main cons:
If you use database and want to increment column after image loads than a person can load your image again and again. So you need to use conditions on every query.
Alternative Solution
Enter this code in footer of page on which you want to show images
A ajax call
$.get("inc_img_view.php?img_id="+<?php echo $img_id; ?>);